forked from twowaits/make-pull-request
-
Notifications
You must be signed in to change notification settings - Fork 0
/
13thOct-4.java
50 lines (50 loc) · 1.57 KB
/
13thOct-4.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.Scanner;
// Java program to fill a matrix with values from 1 to n*n in spiral form
class spiral {
// driver function
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();// n = no. of rows and columns
int a[][] = new int[n][n];//initializing matrix
spiralFill(n, a); // calling function
//printing the matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println("");
}
}
// Fills a[n][n] with values from 1 to n*n in spiral fashion
static void spiralFill(int n, int a[][]) {
// Initialize value to be filled in matrix
int val = 1;
/* k - starting row index
row - ending row index
l - starting column index
col - ending column index */
int k = 0, l = 0,row = n, col = n;
while (k < row && l < col) {
for (int i = l; i < col; ++i) {
a[k][i] = val++;
}
k++;
for (int i = k; i < row; ++i) {
a[i][col - 1] = val++;
}
col--;
if (k < row) {
for (int i = col - 1; i >= l; --i) {
a[row - 1][i] = val++;
}
row--;
}
if (l < col) {
for (int i = row - 1; i >= k; --i) {
a[i][l] = val++;
}
l++;
}
}
}
}