Sie sind auf Seite 1von 3

SPIRAL MATRIX

Q: Write a program to fill up a spiral matrix. Example: Enter no. Of rows: 4 Enter no. of cols.: 4 The spiral matrix is: 1 12 11 10 2 13 16 9 3 14 15 8 4 5 6 7 CODE: import java.io.*; class Spiral_Matrix { public static void main()throws IOException { int row,col,r,c,ci,ri,rlmt,j,clmt,p=1; int a[][]=new int[10][10]; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter no. of rows: "); row=Integer.parseInt(br.readLine()); System.out.print("Enter no. of cols: "); col=Integer.parseInt(br.readLine()); rlmt=row; clmt=col-1; r=-1; c=0; ri=1; ci=1; while(p<=row*col) { for(j=1;j<=rlmt;j++) { r=r+ri; a[r][c]=p++; } for(j=1;j<=clmt;j++) { c=c+ci;

a[r][c]=p++; } rlmt--; clmt--; ri=-ri; ci=-ci; } System.out.println("The Spiral Matrix is:"); for(int i=0;i<row;i++) { for(int k=0;k<col;k++) { System.out.print(a[i][k]+" "); } System.out.println(); } } } OUTPUT: Enter no. of row: 10 Enter no. of cols.: 8 The Spiral Matrix is: 1 2 3 4 5 6 7 8 9 10 32 33 34 35 36 37 38 39 40 11 31 56 57 58 59 60 61 62 41 12 30 55 72 73 74 75 76 63 42 13 29 54 71 80 79 78 77 64 43 14 28 53 70 69 68 67 66 65 44 15 27 52 51 50 49 48 47 46 45 16 26 25 24 23 22 21 20 19 18 17

Algorithm 1. 2. 3. 4. 5. Declare the necessary package. Declare the class. Declare the required variables; Take the size of the matrix from the user. Initialize the variables. Ex => rlmt = row, clmt = col-1, r = -1, c=0, ri=1,ci=1 and p=1

6. Run a while loop till p <=row x column 7. Take a variable starting from 1 to fill the array. 8. Take two conditions one to fill the rows of the array and the other for filling the columns of the array. 9. Go on increasing the value of the variable to fill the array. 10. Print the resultant array. Variable Listing VARIABLE a row col r c rlmt clmt ri ci p TYPE int[][] int int int int int int int int int SCOPE main() main() main() main() main() main() main() main() main() main() DESCRIPTION storing the array no. of rows of the array no. of columns of the array for rows for columns row element column element row index column index to fill the array with value.

Das könnte Ihnen auch gefallen