deno.land / x / masx200_leetcode_test@10.6.5 / shortest-path-in-a-hidden-grid / index.ts

نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { GridMaster } from "./GridMaster.ts";
export default function findShortestPath(master: GridMaster): number { const key = JSON.stringify([0, 0]); const grid: Map<string, number> = new Map();
const end: number[] = []; grid.set(key, -1); dfs(0, 0, new Set<string>().add(key)); function dfs( row: number, col: number, visited: Set<string>, ) { const key = JSON.stringify([row, col]); if (master.isTarget()) { grid.set(key, 2); end[0] = row; end[1] = col; } else { grid.set(key, 1); }
for (const [a, b, x, y] of directions) { const nr = row + a; const nc = col + b; const str = JSON.stringify([nr, nc]); if (!visited.has(str) && master.canMove(x)) { visited.add(str); master.move(x); dfs(nr, nc, visited); master.move(y); } } }
if (end.length === 0) return -1; function bfs( pos: [number, number][], distance: number, visited: Set<string>, ): number { const temp: [number, number][] = []; for (const [row, col] of pos) { const key = JSON.stringify([row, col]); if (grid.get(key) === 2) { return distance; } for (const [a, b] of directions) { const nr = row + a; const nc = col + b; const str = JSON.stringify([nr, nc]); if (!visited.has(str) && grid.get(str) !== 0) { visited.add(str); temp.push([nr, nc]); } } } if (temp.length) return bfs(temp, distance + 1, visited); return -1; } const distance = bfs([[0, 0]], 0, new Set<string>().add(key));
return distance;}const directions = [[0, -1, "L", "R"], [0, 1, "R", "L"], [-1, 0, "U", "D"], [ 1, 0, "D", "U",]] as const;
masx200_leetcode_test

Version Info

Tagged at
a year ago