Skip to content

Commit 530f0b4

Browse files
committed
Create 1162.地图分析.js
1 parent fbf4ce3 commit 530f0b4

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

1162.地图分析.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @param {number[][]} grid
3+
* @return {number}
4+
*/
5+
var maxDistance = function(grid) {
6+
const queue = [];
7+
for (let i = 0; i < grid.length; i++) {
8+
for (let j = 0; j < grid[i].length; j++) {
9+
if (grid[i][j] === 1) {
10+
queue.push([i, j, 0]);
11+
}
12+
}
13+
}
14+
if (queue.length === 0 || queue.length === grid.length * grid[0].length) {
15+
return -1;
16+
}
17+
18+
let result = 0;
19+
while (queue.length) {
20+
const [x, y, z] = queue.shift();
21+
result = Math.max(result, z);
22+
if (grid[x - 1] && grid[x - 1][y] === 0) {
23+
grid[x - 1][y] = 1;
24+
queue.push([x - 1, y, z + 1]);
25+
}
26+
if (grid[x + 1] && grid[x + 1][y] === 0) {
27+
grid[x + 1][y] = 1;
28+
queue.push([x + 1, y, z + 1]);
29+
}
30+
if (grid[x][y - 1] === 0) {
31+
grid[x][y - 1] = 1;
32+
queue.push([x, y - 1, z + 1]);
33+
}
34+
if (grid[x][y + 1] === 0) {
35+
grid[x][y + 1] = 1;
36+
queue.push([x, y + 1, z + 1]);
37+
}
38+
}
39+
return result;
40+
};

0 commit comments

Comments
 (0)