Spiral Matrix
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