leetcode-spiral-matrix-i-ii

Verbatim https://www.dazhuanlan.com/2019/08/26/5d62fafb4de84/


Subject to the effect

  https://leetcode.com/problems/spiral-matrix/

  https://leetcode.com/problems/spiral-matrix-ii/

  These two questions is essentially a question, are generates print matrix or spiral

Topic analysis

  I was beginning to realize each row or each column a few prints, leaving the next column or the next line treatment, this has led finally, a special judge in the end is the remaining 1 row / column, or two rows / columns. The code does not result in an extremely elegant, although AC. I think the goal is not just brush leetcode AC, but also to the pursuit of time / space complexity, and elegant code. Read overwhelmingly answer disscuss area, each is a simple "cut" rows or columns can be very elegant solution out. As Spiral Matrix II but more simply, the subject of the request is to generate a square spiral, it is possible to almost completely code reuse.

Code

  Spiral Matrix:

      
      
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
      
      
public class {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[ 0].length == 0) {
return years;
}
int m = matrix.length;
int n = matrix[ 0].length;
int up = 0;
int down = m - 1;
int left = 0;
int right = n - 1;
while ( true) {
for ( int col = left; col <= right; col++) {
ans.add(matrix[up][col]);
}
up++;
if (up > down) {
break;
}
for ( int row = up; row <= down; row++) {
ans.add(matrix[row][right]);
}
right--;
if (right < left) {
break;
}
for ( int col = right; col >= left; col--) {
ans.add(matrix[down][col]);
}
down--;
if (down < up) {
break;
}
for ( int row = down; row >= up; row--) {
ans.add(matrix[row][left]);
}
left++;
if (left > right) {
break;
}
}
return ans;
}
}

  Spiral Matrix II:

      
      
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
      
      
public class Solution {
public int[][] generateMatrix( int n) {
int[][] matrix = new int[n][n];
int up = 0;
int down = n - 1;
int left = 0;
int right = n - 1;
int c = 0;
while ( true) {
for ( int col = left; col <= right; col++) {
matrix[up][col] = ++c;
}
up++;
if (up > down) {
break;
}
for ( int row = up; row <= down; row++) {
matrix[row][right] = ++c;
}
right--;
if (right < left) {
break;
}
for ( int col = right; col >= left; col--) {
matrix[down][col] = ++c;
}
down--;
if (down < up) {
break;
}
for ( int row = down; row >= up; row--) {
matrix[row][left] = ++c;
}
left++;
if (left > right) {
break;
}
}
return matrix;
}
}

Guess you like

Origin www.cnblogs.com/petewell/p/11410445.html