Skip to content

Commit 21dedca

Browse files
feat: word-search ํ’€์ด
1 parent c47adc0 commit 21dedca

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
var exist = function(board, word) {
7+
//word๋ฅผ ์ˆœํšŒํ•ด์„œ board์˜ x,y๋ฅผ ์กฐ์ ˆํ•˜์—ฌ, ๊ฐ’์ด ์žˆ์œผ๋ฉด ๊ณ„์† true
8+
const xLength = board[0].length;
9+
const yLength = board.length
10+
11+
// ์ฒดํฌ ๋ฐฐ์—ด: ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ €์žฅ. ๊ฐ DFS๋งˆ๋‹ค ์ƒˆ๋กœ ์ดˆ๊ธฐํ™”๋  ํ•„์š”๋Š” ์—†์Œ (DFS ๋‚ด์—์„œ ๋ฐฑํŠธ๋ž˜ํ‚น ์ฒ˜๋ฆฌํ•˜๋ฏ€๋กœ)
12+
const check = Array.from({ length: yLength }, () => Array(xLength).fill(false));
13+
14+
15+
// ๋‹จ์–ด์˜ ์ฒซ ๊ธ€์ž์™€ ์ผ์น˜ํ•˜๋Š” ์‹œ์ž‘์ ์„ ๋ชจ๋‘ ์ˆ˜์ง‘
16+
const startPoints = []
17+
for(let i = 0; i<xLength;i++){
18+
for(let j = 0; j<yLength;j++){
19+
if(board[j][i] == word[0]){
20+
startPoints.push([j,i])
21+
}
22+
}
23+
}
24+
// ๊ฐ ์‹œ์ž‘์ ์—์„œ DFS ์‹œ๋„
25+
for(let startPoint of startPoints){
26+
// ์ž˜๋ชป๋œ ๊ธธ๋กœ ๊ฐ€๋Š” ๊ฒฝ์šฐ๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋ฐฑํŠธ๋ ‰ํ‚น์€ ๋ฌด์กฐ๊ฑด ํ•„์š”ํ•˜๋‹ค.
27+
if(backTracking(startPoint,board,word,check)) return true
28+
}
29+
30+
return false
31+
};
32+
33+
function backTracking(startPoint,board,word,check){
34+
const xLength = board[0].length;
35+
const yLength = board.length
36+
const upDownLeftRight = [[-1,0],[1,0],[0,-1],[0,1]]
37+
//์Šคํƒ€ํŠธ ํฌ์ธํŠธ๋ถ€ํ„ฐ ํ•ด์„œ, ์™„์„ฑ์ด ๊ฐ€๋Šฅํ•œ์ง€๋ฅผ dfs๋ฅผ ํ†ตํ•ด์„œ ์ง„ํ–‰ํ•œ๋‹ค.
38+
//idx๋Š” ํ˜„์žฌ ํ™•์ธํ•ด์•ผํ•  word์˜ idx์ด๋‹ค.
39+
function dfs(y,x,idx){
40+
if(idx == word.length) return true
41+
42+
if(y < 0 || y >= yLength ||
43+
x < 0 || x >= xLength ||
44+
check[y][x] ||
45+
board[y][x] !== word[idx]
46+
) return false;
47+
48+
check[y][x] = true
49+
// 4๋ฐฉํ–ฅ ํƒ์ƒ‰
50+
for(let [dy,dx] of upDownLeftRight){
51+
//๋งŒ์•ฝ ํƒ€๊ฒŸ์— ํ•ด๋‹นํ•˜๋Š”์ง€๋ฅผ ํ™•์ธ์„ ๋จผ์ € ํ•ด์•ผํ• ๊ฒƒ๊ฐ™์Œ!
52+
if(dfs(y+dy,x+dx,idx+1)) return true //4๋ฐฉํ–ฅ์— ๋Œ€ํ•ด์„œ ๋ชจ๋‘ dfs๋ฅผ ์ง„ํ–‰ํ•œ๋‹ค.
53+
54+
}
55+
56+
//๋ฐฑํŠธ๋ ˆํ‚น
57+
check[y][x] = false;
58+
return false
59+
60+
}
61+
return dfs(...startPoint,0)
62+
}

0 commit comments

Comments
ย (0)