File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -41,4 +41,55 @@ public List<Integer> spiralOrder(int[][] matrix) {
4141 return result ;
4242 }
4343 }
44+
45+ public static class Solution2 {
46+ /**
47+ * My completely original solution on 12/29/2021.
48+ */
49+ public List <Integer > spiralOrder (int [][] matrix ) {
50+ List <Integer > ans = new ArrayList <>();
51+ int m = matrix .length ;
52+ int n = matrix [0 ].length ;
53+ int direction = 0 ;
54+ int total = m * n ;
55+ int j = 0 ;
56+ int i = 0 ;
57+ int lowerRow = 0 ;
58+ int lowerCol = 0 ;
59+ while (ans .size () < total ) {
60+ for (; i < m && i >= lowerRow && j < n && j >= lowerCol ; ) {
61+ ans .add (matrix [i ][j ]);
62+ if (direction == 0 ) {//east
63+ j ++;
64+ } else if (direction == 1 ) {//south
65+ i ++;
66+ } else if (direction == 2 ) {//west
67+ j --;
68+ } else {
69+ i --;//north
70+ }
71+ }
72+ if (direction == 0 ) {
73+ i ++;
74+ j --;
75+ } else if (direction == 1 ) {
76+ j --;
77+ i --;
78+ } else if (direction == 2 ) {
79+ j ++;
80+ i --;
81+ lowerRow ++;
82+ m --;
83+ } else {
84+ i ++;
85+ j ++;
86+ lowerCol ++;
87+ n --;
88+ }
89+ direction ++;
90+ direction %= 4 ;
91+ }
92+ return ans ;
93+ }
94+ }
4495}
You can’t perform that action at this time.
0 commit comments