λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 417 - Pacific Atlantic Water Flow (Medium)

by HandHand 2021. 3. 2.

문제

LeetCode - 417번

풀이 κ³Όμ •

μž…λ ₯으둜 주어진 κ²©μžνŒμ—μ„œ κ°€μž₯μžλ¦¬μ— 도달할 수 μžˆλŠ” μ’Œν‘œλ₯Ό μ°ΎλŠ” BFS λ¬Έμ œμ˜€μŠ΅λ‹ˆλ‹€.

문제 쑰건에 따라 x μ£„ν‘œ ν˜Ήμ€ y μ’Œν‘œ κ°€ 0보닀 μž‘μ•„μ§ˆ κ²½μš°λŠ” pacific 에 ν•΄λ‹Ήν•˜κ³ 
κ·Έ λ°˜λŒ€μ˜ κ²½μš°μ—λŠ” atlantic 에 ν•΄λ‹Ήν•©λ‹ˆλ‹€.

λ”°λΌμ„œ matrix 의 각 μ§€μ λ§ˆλ‹€ BFS λ₯Ό μˆ˜ν–‰ν•˜λ©° pacific κ³Ό atlantic 에 λͺ¨λ‘ 도달 κ°€λŠ₯ν•œ κ²½μš°μ—λ§Œ
ν•΄λ‹Ή μ£„ν‘œκ°’μ„ κΈ°λ‘ν•˜μ—¬ 닡을 ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

μ΄λ•Œ μΈμ ‘ν•œ 지역에 λŒ€ν•΄μ„œ 값이 κ°™κ±°λ‚˜ μž‘μ„ κ²½μš°μ—λ§Œ 이동할 수 μžˆλ‹€λŠ” 것에 μœ μ˜ν•˜λ„λ‘ ν•©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {number[][]} matrix
 * @return {number[][]}
 */
var pacificAtlantic = function (matrix) {
  if (!matrix.length) return [];

  const M = matrix.length;
  const N = matrix[0].length;

  // 각 지점을 탐색해본닀
  const ans = [];
  for (let x = 0; x < M; x++) {
    for (let y = 0; y < N; y++) {
      if (bfs(matrix, x, y, M, N)) {
        ans.push([x, y]);
      }
    }
  }

  return ans;
};

const dx = [0, 0, 1, -1];
const dy = [1, -1, 0, 0];

function bfs(matrix, x, y, M, N) {
  const q = [];
  const visit = new Array(M).fill(null).map((_) => new Array(N).fill(0));

  q.push([x, y]);
  visit[x][y] = 1;

  let pacific = false;
  let atlantic = false;

  while (q.length) {
    let [x, y] = q.shift();

    for (let i = 0; i < 4; i++) {
      const nx = x + dx[i],
        ny = y + dy[i];

      // pacific, atlantic, in-cell
      if (nx < 0 || ny < 0) {
        pacific = true;
      } else if (nx >= M || ny >= N) {
        atlantic = true;
      } else if (!visit[nx][ny] && matrix[x][y] >= matrix[nx][ny]) {
        visit[nx][ny] = 1;
        q.push([nx, ny]);
      }
    }
  }

  return pacific && atlantic;
}
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€