Algolithm-Leetcode/Math & Geometry
Spiral Matrix
꿀잠마스터
2026. 8. 14. 00:46
https://leetcode.com/problems/spiral-matrix/
Spiral Matrix - LeetCode
Can you solve this real interview question? Spiral Matrix - Given an m x n matrix, return all elements of the matrix in spiral order. Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg] Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Outpu
leetcode.com
주어진 매트릭스를 주어진 방식으로 안으로 순회하며 값을 리스트에 담아 리턴하는 문제이다.
행과 열의 방향을 배열로 하여 돌아갈 방향을 정해줄 수 있다.
int[] dr = {0, 1, 0, -1};
int[] dc = {1, 0, -1, 0};
int dir = 0;
int nextRow = curRow + dr[dir];
int nextCol = curCol + dc[dir];
위와 같은 형식으로 dir의 값 0~3에 따라 다음 좌표의 행과 열을 이동할 수 있다. dr, dc 의 인덱스별 값에 따라 위치를 지정해줄 수 있으며 문제에서 주어진 방식으로 순서대로 회전하기 위해서 위 코드와 같은 순서로 배열의 값을 지정해주었다.
그 이후 회전하는 타이밍을 정해야 했다. 회전하는 타이밍은 벽에 막히거나 또는 다음 위치가 이미 방문할 위치일 경우이다. 이를 위해서 매트릭스의 범위와 visited 배열을 이용하여 체크해주었다. 아래는 해결한 전체 코드이다.
import java.util.*;
public class Solution {
static int[] dr = {0, 1, 0, -1};
static int[] dc = {1, 0, -1, 0};
static boolean[][] visited;
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> answer = new ArrayList<>();
visited = new boolean[matrix.length][matrix[0].length];
int r = 0;
int c = 0;
int dir = 0;
while(isValidDirection(matrix, r, c)){
visited[r][c] = true;
answer.add(matrix[r][c]);
int nextr = r + dr[dir];
int nextc = c + dc[dir];
if(!isValidDirection(matrix, nextr, nextc)){
dir = (dir + 1) % 4; // 0 - 우, 1 - 하, 2 - 좌, 3 - 상
nextr = r + dr[dir];
nextc = c + dc[dir];
}
r = nextr;
c = nextc;
}
return answer;
}
private boolean isValidDirection(int[][] matrix, int r, int c){
return r >= 0 && r < matrix.length
&& c >= 0 && c < matrix[0].length
&& !visited[r][c];
}
}