λ¬Έμ
νμ΄ κ³Όμ
μ
λ ₯μΌλ‘ μ£Όμ΄μ§ 격μνμμ κ°μ₯μ리μ λλ¬ν μ μλ μ’νλ₯Ό μ°Ύλ 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;
}
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 20 - Valid Parentheses (Easy) (0) | 2021.03.02 |
---|---|
LeetCode 787 - Cheapest Flights Within K Stops (Medium) (0) | 2021.03.02 |
LeetCode 17 - Letter Combinations of a Phone Number (Medium) (0) | 2021.03.02 |
LeetCode 230 - Kth Smallest Element in a BST (Medium) (0) | 2021.03.02 |
LeetCode 198 - House Robber (Easy) (0) | 2021.03.02 |
π¬ λκΈ