Categories
Class 11 Class 12

Spiral Matrix Anticlockwise in Java

Write a program in Java to create a two-dimensional array of size [n × n].

The value of n is entered by the user and make sure that 2 < n < 10.

Now fill the natural numbers into this matrix in a circular or spiral fashion starting from 1 to n2 as illustrated below:

INPUT:
N = 5
OUTPUT:

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
import java.io.*;
class Spiral{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Matrix size: ");
        int n = Integer.parseInt(br.readLine());
        if(n < 3 || n > 9){
            System.out.println("Size out of range!");
            return;
        }
        int a[][] = new int[n][n];
        int value = n * n;
        int r1 = n - 1;
        int r2 = 0;
        int c1 = 0;
        int c2 = n - 1;
        while(value >= 1){
            for(int i = r1; i >= r2; i--)
                a[i][c1] = value--;
            for(int i = c1 + 1; i <= c2; i++)
                a[r2][i] = value--;
            for(int i = r2 + 1; i <= r1; i++) 
                a[i][c2] = value--; 
            for(int i = c2 - 1; i >= c1 + 1; i--)
                a[r1][i] = value--;
            r1--;
            r2++;
            c1++;
            c2--;
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++){
                System.out.print(a[i][j] + "\t");
            }
            System.out.println();
        }
    }
}