11 Jun 2015

Algo #117: Concentric Squares

Problem Statement: 
           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.

Answer:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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();
  }
 }

Solution was suggested by Ashish Mishra
Please post your suggestions and comments.
Happy Coding !! :)