๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/leetcode

LeetCode 54 - Spiral Matrix (Medium)

by HandHand 2021. 3. 3.

๋ฌธ์ œ

LeetCode - 54๋ฒˆ

ํ’€์ด ๊ณผ์ •

2์ฐจ์› ๋ฐฐ์—ด ์„ ์ด์šฉํ•œ ๊ตฌํ˜„ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋ฐฐ์—ด์˜ ์›€์ง์ž„์—์„œ ๊ทœ์น™์„ ์ฐพ์•„ ํ™”์ „ํ•˜๋Š” ์‹œ๋ฎฌ๋ ˆ์ด์…˜์„ ํ•  ์ˆ˜๋„ ์žˆ์ง€๋งŒ ์ข€ ๋” ๊ฐ„๋‹จํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ
DFS ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ชจ๋“  ์œ„์น˜๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์‹œ์ž‘์ง€์  (0, 0) ์—์„œ๋ถ€ํ„ฐ ์˜ค๋ฅธ์ชฝ, ์•„๋ž˜์ชฝ, ์™ผ์ชฝ, ์œ„์ชฝ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฉํ–ฅ์„ ํ‹€์–ด๊ฐ€๋ฉฐ ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค.
์ด๋•Œ ๋ฐฉํ–ฅ์„ ์ „ํ™˜ํ•˜๋Š” ์‹œ์ ์€ ๋ฐฐ์—ด์„ ๋ฒ—์–ด๋‚˜๊ฑฐ๋‚˜ ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ์ง€์ ์„ ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜๋ ค๊ณ  ํ•  ๋•Œ์ž…๋‹ˆ๋‹ค.

์ด๋ฅผ ํ™œ์šฉํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์ฝ”๋“œ๋กœ ์›ํ•˜๋Š” ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
var spiralOrder = function (matrix) {
  const m = matrix.length;
  const n = matrix[0].length;
  const dx = [0, 1, 0, -1];
  const dy = [1, 0, -1, 0];
  const answer = [];
  const visit = Array.from(Array(m), () => Array(n).fill(false));

  function inRange(x, y) {
    return 0 <= x && x < m && 0 <= y && y < n;
  }

  function dfs(x, y, dir) {
    if (!inRange(x, y) || visit[x][y]) return;

    visit[x][y] = true;
    answer.push(matrix[x][y]);

    let nx = x + dx[dir];
    let ny = y + dy[dir];

    if (inRange(nx, ny) && !visit[nx][ny]) {
      dfs(nx, ny, dir);
    } else {
      dir = (dir + 1) % 4;
      nx = x + dx[dir];
      ny = y + dy[dir];

      dfs(nx, ny, dir);
    }
  }

  dfs(0, 0, 0);

  return answer;
};
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > leetcode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

LeetCode 226 - Invert Binary Tree (Easy)  (0) 2021.03.03
LeetCode 406 - Queue Reconstruction by Height (Medium)  (0) 2021.03.03
LeetCode 279 - Perfect Squares (Medium)  (0) 2021.03.03
LeetCode 94 - Binary Tree Inorder Traversal (Medium)  (0) 2021.03.03
LeetCode 394 - Decode String (Medium)  (0) 2021.03.03

๐Ÿ’ฌ ๋Œ“๊ธ€