Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
Example 1 :
1
2
3
4
5
6
7
8
9
Input : matrix = [[1,2,3],[4,5,6][7,8,9]] Output : [1,2,3,6,9,8,7,4,5]
Example 2 :
1
2
3
4
5
6
7
8
9
10
11
12
Input : matrix = [[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,8]
์๋ฃ๊ตฌ์กฐ : List์ ๋ณ์ 4๊ฐ ์ด์ฉ(rowStart,rowEnd,colStart,colEnd) ์๊ณ ๋ฆฌ์ฆ 1. ํ๊ณผ ์ด์ด ์ด๋ป๊ฒ ๋ณํํ๋์ง ๋ณธ๋ค. 2. ํ๊ณผ ์ด์ด ๋ฐ๋ ๋๋ง๋ค ๊ทธ๋ค์ ์ฆ๊ฐ์์ ๋ฒ์๊ฐ ๋ฐ๋๊ธฐ ๋๋ฌธ์ ์ด ๋ฒ์๋ฅผ ์ฒดํฌํ๊ธฐ ์ํด rowStart,rowEnd,colStart,colEnd๋ฅผ ์ด์ฉํ๋ค!
์๊ณ ๋ฆฌ์ฆ์ java๋ก ๊ตฌํ
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
//1. ๊ทธ๋ฆ ์์ฑ
int rowStart = 0,colStart = 0;
int rowEnd = matrix.length-1;//3-1=2.
int colEnd = matrix[0].length-1;//4-1=3.
List<Integer> result = new ArrayList<>();
if(matrix == null || matrix.length == 0) return result;
while(rowStart <= rowEnd && colStart <= colEnd) {
//right. ํ๊ณ ์ , ์ด์ฆ๊ฐ
for(int i=colStart; i <= colEnd; i++) {
result.add(matrix[rowStart][i]);
}
rowStart++;
//down. ์ด๊ณ ์ , ํ์ฆ๊ฐ
for(int i=rowStart; i <= rowEnd; i++) {
result.add(matrix[i][colEnd]);
}
colEnd--;
//left. ํ๊ณ ์ , ์ด๊ฐ์!
if(rowStart <= rowEnd) {
for(int i=colEnd; i >= colStart ;i--) {
result.add(matrix[rowEnd][i]);
}
}
rowEnd--;//rowStart < rowEnd!!!
//up. ์ด๊ณ ์ , ํ๊ฐ์!
if(colStart <= colEnd) {
if(rowStart <= rowEnd) {
for(int i = rowEnd; i >= rowStart; i--) {
result.add(matrix[i][colStart]);
}
}
}
colStart++;//colStart < colEnd!!!
// //2nd right. ํ๊ณ ์ , ์ด์ฆ๊ฐ!
// for(int i= colStart; i <= colEnd ; i++) {
// result.add(matrix[rowStart][i]);
// }
}
return result;
}
}
Last updated
Was this helpful?