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?