-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1091-shortest-path-in-binary-matrix.js
More file actions
60 lines (50 loc) · 1.4 KB
/
1091-shortest-path-in-binary-matrix.js
File metadata and controls
60 lines (50 loc) · 1.4 KB
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
/**
* Shortest Path In Binary Matrix
* Time Complexity: O(N^2)
* Space Complexity: O(N^2)
*/
var shortestPathBinaryMatrix = function (grid) {
const gridDimension = grid.length;
if (grid[0][0] === 1 || grid[gridDimension - 1][gridDimension - 1] === 1) {
return -1;
}
const pathSearchQueue = [];
pathSearchQueue.push([0, 0, 1]);
const movementVectors = [
[-1, -1],
[-1, 0],
[-1, 1],
[0, -1],
[0, 1],
[1, -1],
[1, 0],
[1, 1],
];
grid[0][0] = 1;
while (pathSearchQueue.length > 0) {
const pathHead = pathSearchQueue.shift();
const presentRow = pathHead[0];
const presentCol = pathHead[1];
const presentLength = pathHead[2];
if (presentRow === gridDimension - 1 && presentCol === gridDimension - 1) {
return presentLength;
}
for (let idx = 0; idx < movementVectors.length; idx++) {
const rowOffset = movementVectors[idx][0];
const colOffset = movementVectors[idx][1];
const nextCellRow = presentRow + rowOffset;
const nextCellCol = presentCol + colOffset;
if (
nextCellRow >= 0 &&
nextCellRow < gridDimension &&
nextCellCol >= 0 &&
nextCellCol < gridDimension &&
grid[nextCellRow][nextCellCol] === 0
) {
grid[nextCellRow][nextCellCol] = 1;
pathSearchQueue.push([nextCellRow, nextCellCol, presentLength + 1]);
}
}
}
return -1;
};