Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit af5de50

Browse files
level bfs
1 parent 21c2518 commit af5de50

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

‎leetcode/317.shortest_distance_from_all_buildings/317.ShortestDistancefromAllBuildings_henrytien.cpp‎

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -29,43 +29,48 @@ class Solution
2929
// Calculate every building point to landing point distance, and get the minm.
3030
int m = grid.size(), n = grid[0].size();
3131
vector<int> direction = {-1, 0, 1, 0, -1}; // left up right down
32-
auto total = grid;
32+
vector<vector<int>> distance(m, vector<int>(n, 0));
33+
3334
int min_dist = 0, walk = 0;
3435
for (int i = 0; i < m; i++)
3536
{
3637
for (int j = 0; j < n; j++)
3738
{
3839
if (grid[i][j] == 1)
3940
{
40-
min_dist = -1;
41-
auto dist = grid;
41+
// Note this is initialized to -1, so when a building is not reachable it will be -1 at the end
42+
min_dist = INT_MAX;
4243
queue<pair<int, int>> que;
4344

4445
que.emplace(i, j);
45-
46+
int level = 1;
4647
while (!que.empty())
4748
{
48-
auto land = que.front();
49-
que.pop();
49+
int len = que.size();
5050

51-
for (int k = 0; k < 4; k++)
51+
for (int k = 0; k < len; k++)
5252
{
53-
int x = land.first + direction[k];
54-
int y = land.second + direction[k + 1];
55-
if (x >= 0 && x < m && y >= 0 && y < n && walk == grid[x][y])
53+
auto curr = que.front();
54+
que.pop();
55+
for (int l = 0; l < 4; l++)
5656
{
57-
grid[x][y]--;
58-
dist[x][y] = dist[land.first][land.second] + 1;
59-
total[x][y] += dist[x][y] - 1;
60-
que.emplace(x, y);
61-
if (min_dist < 0 || min_dist > total[x][y])
57+
int x = curr.first + direction[l];
58+
int y = curr.second + direction[l + 1];
59+
if (x >= 0 && x < m && y >= 0 && y < n && walk == grid[x][y])
6260
{
63-
min_dist = total[x][y];
61+
grid[x][y]--;
62+
distance[x][y] += level;
63+
64+
que.emplace(x, y);
65+
min_dist = min(min_dist, distance[x][y]);
6466
}
6567
}
6668
}
69+
level++;
6770
}
6871
walk--;
72+
if (min_dist == INT_MAX)
73+
return -1;
6974
}
7075
}
7176
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /