- LeetCode 최소 하루에 하나는 풀자는 마인드
- 사용언어: JAVA
54. Spiral Matrix
풀이
- 방법: 가장 바깥쪽 top, bottom, left, right를 정의하고 한번 반복할때 마다 끝값을 옮겨서 껍질벗기듯 바깥 -> 안쪽으로 순회
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList();
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while(top <= bottom && left <= right){
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++;
for(int i = top; i <= bottom; i++){
result.add(matrix[i][right]);
}
right--;
if(top <= bottom){
for(int i = right; i >= left ; i--){
result.add(matrix[bottom][i]);
}
bottom--;
}
if(left <= right){
for(int i = bottom; i >= top; i--){
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
}