BFS โ
Queue
๋ฅผ ์ด์ฉ- ์กฐ๊ฑด์ ๋๋ฌํ์๋ ์๊ตฌํ๋ ๊ฐ์ ์ถ๋ ฅ๊ฐ๋ฅ
- ์ต๋จ๊ฑฐ๋ฆฌ ํ์์์ ์ฌ์ฉ
- ๋ฐฉ๋ฌธ ์ฒดํฌ
- ๋ฐฉ๋ฌธํด์ผํ ๊ฒฝ๋ก๋ฅผ Queue์ ๋ฃ์ด๋๋ ๋์์ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผ ์ค๋ณต ๊ฒฝ๋ก๊ฐ Queue์ ๋ด๊ธฐ์ง ์๋๋ค.
- Queue์ ํ์
์ ์ฃผ๋ก Class๋ฅผ ์ ์ธํ์ฌ
Index
,Count
๋ฅผ ์์ฑ์ผ๋ก ๋๊ณ ๋ชฉํ ๊ฒฝ๋ก์ ๋๋ฌํ์๋ Count๋ฅผ ์ถ๋ ฅํ๋ ๋ฐฉ์
๊ตฌํ โ
javascript
let arr = [
[0, 0, 0, 0, 0],
[0, 1, 1, 1, 0],
[0, 1, 0, 0, 0],
[0, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
]
const directions = [
[-1, 0],
[0, 1],
[1, 0],
[0, -1],
]
// arr ๋ฐฐ์ด์ [0][0]์์ ์ถ๋ฐํด์ [4][4]๊น์ง ๋์ฐฉํ๋ ๋ก์ง (0: ๊ธธ, 1: ๋ฒฝ), ๊ธธ์ ํตํด์๋ง ์ด๋๊ฐ๋ฅ
const searchHandler = () => {
console.log('Breadth First Search')
const bfsResult = BFS(
Array.from(Array(5), () => Array(5).fill(false)),
arr
)
console.log('bfsResult', bfsResult)
console.log('Depth First Search')
let dfsResult = [Number.MAX_SAFE_INTEGER]
DFS(
0,
0,
0,
dfsResult,
Array.from(Array(5), () => Array(5).fill(false))
)
console.log('dfsResult', dfsResult[0])
}
const BFS = (visited, arr) => {
const start = [0, 0, 0]
let queue = [start]
visited[0][0] = true
while (queue.length) {
const pos = queue.shift()
if (pos[0] === arr.length - 1 && pos[1] === arr[0].length - 1) return pos[2]
for (let dir of directions) {
const ty = dir[0] + pos[0]
const tx = dir[1] + pos[1]
if (0 <= ty && ty < arr.length && 0 <= tx && tx < arr[0].length) {
if (visited[ty][tx]) continue
if (arr[ty][tx] === 1) continue
visited[ty][tx] = true
queue.push([ty, tx, pos[2] + 1])
}
}
}
}
const DFS = (y, x, depth, answer, visited) => {
if (arr[y][x] === 1) return
if (visited[y][x]) return
if (answer[0] < depth) return
visited[y][x] = true
console.log(y, x, depth)
if (y === arr.length - 1 && x === arr[0].length - 1) {
answer[0] = Math.min(answer[0], depth)
return
}
for (let dir of directions) {
const ty = dir[0] + y
const tx = dir[1] + x
if (0 <= ty && ty < arr.length && 0 <= tx && tx < arr[0].length) {
DFS(ty, tx, depth + 1, answer, visited)
}
}
}
searchHandler()