Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example
Solution 1: Simulation
- Use two 1X4 arrays to mark the moving direction of the x and y index.
- Use a mXn array to mark if the number has been visited or not
- If the number has been visited, we should change the moving direction.
Time Complexity: O(N), Space Complexity: O(N)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();
if(matrix == null || matrix.length == 0)
return res;
int m = matrix.length;
int n = matrix[0].length;
boolean[][] visited = new boolean[m][n];
int[] dx = {0, 1, 0, -1};
int[] dy = {1, 0, -1, 0};
int x = 0;
int y = 0;
int di = 0;
for(int i = 0; i < m*n; i++) {
res.add(matrix[x][y]);
visited[x][y] = true;
int nextX = x + dx[di];
int nextY = y + dy[di];
if(0 <= nextY && nextY < n && 0 <= nextX && nextX < m && !visited[nextX][nextY]) {
x = nextX;
y = nextY;
} else {
di = (di+1) % 4;
x += dx[di];
y += dy[di];
}
}
return res;
}
}
Solution 2: layer by layer
Consideration
- We iterate each layer to iterate the matrix
- If the layer row length or column length is 0, the loop ends
3. Be careful for the single row or single column layer situation
Time Complexity: O(N), space complexity: O(N)
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList();
if(matrix == null || matrix.length == 0)
return res;
int m = matrix.length;
int n = matrix[0].length;
int x = 0;
int y = 0;
while(m > 0 && n > 0) {
// for 1Xn array
if(m == 1) {
for(int i = 0; i < n; i++)
res.add(matrix[x][y++]);
break;
// for mX1 array
} else if(n == 1) {
for(int i= 0; i < m; i++)
res.add(matrix[x++][y]);
break;
} else {
for(int i = 0; i < n-1; i++) {
res.add(matrix[x][y++]);
}
for(int i = 0; i < m-1; i++) {
res.add(matrix[x++][y]);
}
for(int i = 0; i < n-1; i++) {
res.add(matrix[x][y--]);
}
for(int i = 0; i < m-1; i++) {
res.add(matrix[x--][y]);
}
x+=1;
y+=1;
m-=2;
n-=2;
}
}
return res;
}
}
References