Matrix Circular or Spiral Fill in Java

Write a program to create a square matrix of type integer of size ‘n’, where the value of ‘n’ is input by the user. Now fill the matrix with natural numbers in circular/spiral fashion in clockwise order, starting from index [0, 0], and display the generated matrix.

Example:
INPUT:
N = 5
OUTPUT:

1    2    3    4    5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
import java.io.*;
class CircularFill{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        int a[][] = new int[n][n];
        int value = 1;
        int row1 = 0;
        int col1 = 0;
        int row2 = n - 1;
        int col2 = n - 1;
        int i = 0;
        int j = 0;
        while(value <= n * n){
            for(i = col1; i <= col2; i++)
                a[row1][i] = value++;
            for(i = row1 + 1; i <= row2; i++)
                a[i][col2] = value++;
            for(i = col2 - 1; i >= col1; i--)
                a[row2][i] = value++;
            for(i = row2 - 1; i >= row1 + 1; i--)
                a[i][col1] = value++;
            col1++;
            col2--;
            row1++;
            row2--;
        }
        System.out.println("Generated Matrix:");
        for(i = 0; i < n; i++){
            for(j = 0; j < n; j++)
                System.out.print(a[i][j] + "\t");
            System.out.println();
        }
    }
}

2 thoughts on “Matrix Circular or Spiral Fill in Java”

  1. Sir,a program is given which states that:
    WAP in java to create a 2D array of size n x n (n >2 & n < 10).Now fill the numbers in a circular fashion (anti-clockwise) with natural numbers from 1 to n^2,as illustrated below:
    E.g.if n=5,n^2=25,then the array is filled as:
    21 20 19 18 17
    22 7 6 5 16
    23 8 1 4 15
    24 9 2 3 14
    25 10 11 12 13

Leave a Reply

%d bloggers like this: