본문 바로가기

Algorithm/LeetCode

[배열/시뮬레이션] 59. Spiral Matrix II

문제 바로가기

 

Spiral Matrix II - LeetCode

Can you solve this real interview question? Spiral Matrix II - Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.   Example 1: [https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg] Input: n = 3 O

leetcode.com


54번 문제의 친구입니다. 얘는 반대로 n 이 주어졌을 때 n x n 크기의 2차원 배열을 만들어주면 됩니다. 시곗방향으로 삥삥 돌면서요.

이딴게 미디움???????????

 

class Solution {
  public int[] dy = {0, 1, 0, -1};
  public int[] dx = {1, 0, -1, 0};
  public int dir = 0;

  public int[][] generateMatrix(int n) {
    int[][] answer = new int[n][n];
    int cy = 0;
    int cx = 0;
    int start = 1;

    answer[cy][cx] = start++;

    while (start <= n * n) {
      int ny = cy + dy[dir];
      int nx = cx + dx[dir];

      if (isIn(ny, nx, n) && answer[ny][nx] == 0) {
        answer[ny][nx] = start++;
        cy = ny;
        cx = nx;
      } else {
        dir = (dir + 1) % 4;
      }
    }

    return answer;
  }

  public boolean isIn(int y, int x, int n) {
    return 0 <= y && y < n && 0 <= x && x < n;
  }
}

 

이동할 방향을 ⇒ ⇓ ⇐ ⇑ 요 방향으로 돌면서 배열을 채워주면 됩니다.ㅋㅋ

얘도 역시 반복문의 종료 조건이 단순합니다. 가장 최근에 배열에 넣은 값이 n * n 이 되면 끝내면 되겠죠.

 

그리고 다음 좌표의 방문 가능 조건은

  1. 배열의 바깥으로 벗어나는지? (isIn())
  2. 이미 방문한 곳인지? (answer[][] == 0)

이렇게 다음에 방문할 수 있는 곳인지 체크하면서 가면 됩니다. 만약 방문할 수 없다면 시곗방향으로 움직일 방향을 수정해주면 됩니다.

 

 

감사합니다~!!