Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
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 left = 0; int right = matrix[0].length - 1;
int up = 0; int down = matrix.length - 1;
int dir = 0; // 0:right, 1:down, 2:left, 3:up
int tempx = 0; int tempy = 0;
result.add(matrix[0][0]);
while(down >= up && right >= left){
switch(dir){
case 0:
while(++tempy <= right){
result.add(matrix[tempx][tempy]);
}
tempy--;
up++;
dir = 1;
break;
case 1:
while(++tempx <= down){
result.add(matrix[tempx][tempy]);
}
tempx--;
right--;
dir = 2;
break;
case 2:
while(--tempy >= left){
result.add(matrix[tempx][tempy]);
}
tempy++;
down--;
dir = 3;
break;
case 3:
while(--tempx >= up){
result.add(matrix[tempx][tempy]);
}
tempx++;
left++;
dir = 0;
break;
default:
break;
}
}
return result;
}
}
还是用了一刷的办法,使用case-switch来控制循环。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new LinkedList<>();
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
int height = matrix.length, width = matrix[0].length;
int up = 0, down = height - 1, left = 0, right = width - 1;
int dir = 0; //0:right, 1:down, 2:left, 3: up
int x = 0, y = 0;
result.add(matrix[0][0]);
while(up <= down && right >= left){
switch(dir){
case 0:
while(++y <= right)
result.add(matrix[x][y]);
up++; y--;
dir = 1;
break;
case 1:
while(++x <= down)
result.add(matrix[x][y]);
right--; x--;
dir = 2;
break;
case 2:
while(--y >= left)
result.add(matrix[x][y]);
down--; y++;
dir = 3;
break;
case 3:
while(--x >= up)
result.add(matrix[x][y]);
left++; x++;
dir = 0;
break;
default:
break;
}
}
return result;
}
}