Skip to content

Commit e6ef357

Browse files
committed
bfs 문제풀이 업데이트
1 parent 0d85936 commit e6ef357

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

part8/2.나이트이동.txt

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
const fs = require("fs")
2+
let input = fs.readFileSync("index.txt").toString().split("\n")
3+
4+
class Queue {
5+
constructor() {
6+
this._arr = []
7+
}
8+
enqueue(item) {
9+
this._arr.push(item)
10+
}
11+
dequeue() {
12+
return this._arr.shift()
13+
}
14+
getLength() {
15+
return this._arr.length
16+
}
17+
}
18+
19+
20+
let testCaseCnt=Number(input.shift())
21+
22+
for(let i=0;i<testCaseCnt;i++){
23+
24+
let n = Number(input[0])
25+
let visited = Array.from(new Array(n), () => new Array(n).fill(0))
26+
27+
let start = input[1].split(" ").map(Number)
28+
let end = input[2].split(" ").map(Number)
29+
30+
function bfs() {
31+
const queue = new Queue()
32+
queue.enqueue(start)
33+
34+
while (queue.getLength() != 0) {
35+
const [x, y] = queue.dequeue()
36+
37+
if (x == end[0] && y == end[1]) {
38+
return visited[x][y]
39+
}
40+
41+
let dx = [-2,-2,-1,-1,1,1,2,2];
42+
let dy = [-1,1,-2,2,-2,2,-1,1];
43+
44+
for (let i = 0; i < 8; i++) {
45+
let nx = x + dx[i];
46+
let ny = y + dy[i];
47+
48+
if (nx < 0 || ny < 0 || nx >= n || ny >= n) {
49+
continue
50+
}
51+
52+
if (visited[nx][ny] == 0) {
53+
visited[nx][ny] = visited[x][y] + 1
54+
queue.enqueue([nx, ny])
55+
}
56+
}
57+
58+
}
59+
}
60+
console.log(bfs())
61+
62+
input=input.slice(3)
63+
}
64+
65+

0 commit comments

Comments
 (0)