Thinking process
http://www.programcreek.com/2013/01/leetcode-spiral-matrix-java/
if row and column are more than one, then there is a cycle
- two position variables, x and y
Mistakes
don't forget to break if the row or column is 1
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
int rows = matrix.length;
int cols = matrix[0].length;
int x = 0;//current row position
int y = 0;//current col position
//[1,2,3]
while (rows > 0 && cols > 0) {
if (rows == 1) {
for (int i = 0; i < cols; ++i) {
result.add(matrix[x][y++]);
}
break;
}
if (cols == 1) {
for (int i = 0; i < rows; ++i) {
result.add(matrix[x++][y]);
}
break;
}
//top, left => right
for (int i = 0; i < cols - 1; ++i) {
result.add(matrix[x][y++]);
}
//right, top => bottom
for (int i = 0; i < rows - 1; ++i) {
result.add(matrix[x++][y]);
}
//bottom, right => left
for (int i = 0; i < cols - 1; ++i) {
result.add(matrix[x][y--]);
}
//left, bottom => top
for (int i = 0; i < rows - 1; ++i) {
result.add(matrix[x--][y]);
}
rows -= 2;
cols -= 2;
x++;
y++;
}
return result;
}
}
Follow up - 59. Spiral Matrix II
public class Solution {
public int[][] generateMatrix(int n) {
int[][] result = new int[n][n];
int x = 0;
int y = 0;
int num = 1;
while (n > 0) {
if (n == 1) {
result[x][y] = num;
break;
}
//top, left => right
for (int i = 0; i < n - 1; ++i) {
result[x][y++] = num;
num++;
}
//right, top => bottom
for (int i = 0; i < n - 1; ++i) {
result[x++][y] = num;
num++;
}
//bottom, right => left
for (int i = 0; i < n - 1; ++i) {
result[x][y--] = num;
num++;
}
//left, bottom => top
for (int i = 0; i < n - 1; ++i) {
result[x--][y] = num;
num++;
}
n -= 2;
x++;
y++;
}
return result;
}
}