Leetcode
2020.04.20 15:04

54. Spiral Matrix

조회 수 217 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

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 result = new ArrayList();
        if(matrix.length < 1){
            return result;
        }
        
        int rows = matrix.length;
        int cols = matrix[0].length;
        
        boolean[][] visit = new boolean[rows][cols];
        int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int d = 0;
        int m = 0;
        int n = 0;
        
        for(int i=0; i<matrix.length * matrix[0].length; i++){
            result.add(matrix[m][n]);
            visit[m][n] = true;
            
            if(dirs[d][0]+m<0 || rows-1<dirs[d][0] + m ||
               dirs[d][1]+n<0 || cols-1<dirs[d][1]+n ||
               visit[dirs[d][0]+m][dirs[d][1]+n] == true){
                d = (d+1)%4;
            }
            m = dirs[d][0] + m;
            n = dirs[d][1] + n;
        }
        
        return result;
    }
}


[문제] https://leetcode.com/problems/spiral-matrix/



?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
37 Leetcode 415. Add Strings hooni 2020.04.28 210
36 Leetcode 7. Reverse Integer hooni 2020.04.28 213
35 Leetcode 206. Reverse Linked List hooni 2020.04.28 221
34 Leetcode 53. Maximum Subarray hooni 2020.04.28 209
33 Leetcode 581. Shortest Unsorted Continuous Subarray hooni 2020.04.28 207
32 Leetcode 852. Peak Index in a Mountain Array hooni 2020.04.28 203
31 Leetcode 350. Intersection of Two Arrays II hooni 2020.04.28 201
30 Leetcode 20. Valid Parentheses hooni 2020.04.25 357
29 Leetcode 38. Count and Say hooni 2020.04.25 191
28 Leetcode 937. Reorder Data in Log Files hooni 2020.04.25 200
27 Leetcode 443. String Compression hooni 2020.04.25 192
26 Leetcode 437. Path Sum III hooni 2020.04.24 235
» Leetcode 54. Spiral Matrix hooni 2020.04.20 217
24 Leetcode 380. Insert Delete GetRandom O(1) hooni 2020.04.18 212
23 Leetcode 542. 01 Matrix hooni 2020.04.18 220
22 Leetcode 139. Word Break hooni 2020.04.18 224
21 Leetcode 126. Word Ladder II hooni 2020.04.17 209
20 Leetcode 238. Product of Array Except Self hooni 2020.04.17 212
19 Leetcode 763. Partition Labels hooni 2020.04.17 256
18 Leetcode 121. Best Time to Buy and Sell Stock hooni 2020.04.17 218
Board Pagination Prev 1 2 3 4 Next
/ 4