λ¬Έμ
νμ΄ κ³Όμ
μ΄μ°¨μ λ°°μ΄μμ μΈμ ν λ¬Έμλ€μ μ΄μ©ν΄μ νΉμ λ¨μ΄λ₯Ό λ§λ€ μ μλμ§ νλ¨νλ λ¬Έμ μ
λλ€. λ°±νΈλνΉ
μ νμ©ν΄μ λ¬Έμκ° μΌμΉνμ§ μμΌλ©΄ λ€μ μμΉλ₯Ό μ°Ύλλ‘ νμμ νλ©΄ λ©λλ€.
λν μνλ λ¨μ΄λ₯Ό μ°ΎμΌλ©΄ λ€λ₯Έ λ¬Έμλ€μ νμνμ§ μκ³ λ°λ‘ true
λ₯Ό λ°ννλλ‘ νμμ΅λλ€.
μ½λ
/**
* @param {character[][]} board
* @param {string} word
* @return {boolean}
*/
var exist = function (board, word) {
const dx = [0, 0, 1, -1];
const dy = [1, -1, 0, 0];
function dfs(x, y, depth, visit) {
if (board[x][y] !== word[depth]) return false;
else if (depth === word.length - 1) return true;
for (let i = 0; i < 4; i++) {
const nx = x + dx[i],
ny = y + dy[i];
if (0 <= nx && nx < board.length && 0 <= ny && ny < board[0].length) {
if (!visit[nx][ny]) {
visit[nx][ny] = 1;
if (dfs(nx, ny, depth + 1, visit)) return true;
visit[nx][ny] = 0;
}
}
}
return false;
}
for (let x = 0; x < board.length; x++) {
for (let y = 0; y < board[0].length; y++) {
if (board[x][y] === word[0]) {
const visit = new Array(board.length)
.fill(0)
.map((_) => new Array(board[0].length).fill(0));
visit[x][y] = 1;
if (dfs(x, y, 0, visit)) return true;
visit[x][y] = 0;
}
}
}
return false;
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 118 - Pascal's Triangle (Easy) (0) | 2021.03.03 |
---|---|
LeetCode 19 - Remove Nth Node From End of List (Medium) (0) | 2021.03.03 |
LeetCode 771 - Jewels and Stones (Easy) (0) | 2021.03.03 |
LeetCode 5 - Longest Palindromic Substring (Medium) (0) | 2021.03.03 |
LeetCode 206 - Reverse Linked List (Easy) (0) | 2021.03.03 |
π¬ λκΈ