Coding Recipies: Algo #117: Concentric Squares
For a given input print concentric squares on console.
Solution :
Multiple solutions are available for this problem, but we will solve this without any additional space.
Here the idea is to calculate the minimum depth of each square from outer boundary.
For a given input print concentric squares on console.
Fig1 : Concentric Squares |
Solution :
Multiple solutions are available for this problem, but we will solve this without any additional space.
Here the idea is to calculate the minimum depth of each square from outer boundary.
public static void concentricSquare(int num) { int size = 2*num-1; for (int row = 1; row <= size; row++) { for (int col = 1; col <= size; col++) { int rowDepth = num - 1 - abs(row - num); int colDepth = num - 1 - abs(col - num); int minDepth = min(rowDepth, colDepth); System.out.print(num - minDepth + " "); } System.out.println(); } }Read full article from Coding Recipies: Algo #117: Concentric Squares