File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed
src/com/blankj/medium/_0059 Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .blankj .medium ._059 ;
2
+
3
+
4
+ public class Solution {
5
+
6
+ public static void main (String [] args ) {
7
+ Solution s = new Solution ();
8
+ s .displayMatrix (s .generateSpiralMatrix (3 ));
9
+ s .displayMatrix (s .generateSpiralMatrix (4 ));
10
+ }
11
+
12
+ private void displayMatrix (int [][] matrix ) {
13
+ for (int [] column : matrix ) {
14
+ for (int e : column ) {
15
+ System .out .print (e );
16
+ System .out .print (" " );
17
+ }
18
+ System .out .println ("\n " );
19
+ }
20
+ }
21
+
22
+ public int [][] generateSpiralMatrix (int n ) {
23
+ int [][] res = new int [n ][n ];
24
+ int count = 1 ;
25
+ int top = 0 ;
26
+ int right = 0 ;
27
+ int left = n ;
28
+ int bottom = n ;
29
+ int total = n * n ;
30
+ while (count <= total ) {
31
+ int i = top ;
32
+ int j = right ;
33
+ for (; j < left ; j ++) {
34
+ res [i ][j ] = count ++;
35
+ }
36
+ j = left - 1 ;
37
+ for (i = top + 1 ; i < bottom ; i ++) {
38
+ res [i ][j ] = count ++;
39
+ }
40
+ i = bottom - 1 ;
41
+ for (j = left - 2 ; j >= right ; j --) {
42
+ res [i ][j ] = count ++;
43
+ }
44
+ j = right ;
45
+ for (i = bottom - 2 ; i > top ; i --) {
46
+ res [i ][j ] = count ++;
47
+ }
48
+ top = top + 1 ;
49
+ left = left - 1 ;
50
+ bottom = bottom - 1 ;
51
+ right = right + 1 ;
52
+ }
53
+
54
+ return res ;
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments