1
+ // Source : https://leetcode.com/problems/shortest-distance-from-all-buildings/
2
+ // Author : henrytien
3
+ // Date : 2022-02-05
4
+
5
+ /* ****************************************************************************************************
6
+ *
7
+ * You are given an m x n grid grid of values 0, 1, or 2, where:
8
+
9
+ each 0 marks an empty land that you can pass by freely,
10
+ each 1 marks a building that you cannot pass through, and
11
+ each 2 marks an obstacle that you cannot pass through.
12
+ You want to build a house on an empty land that reaches all buildings in the shortest total travel
13
+ distance. You can only move up, down, left, and right.
14
+
15
+ Return the shortest travel distance for such a house. If it is not possible to build such a house
16
+ according to the above rules, return -1.
17
+
18
+ The total travel distance is the sum of the distances between the houses of the friends and the meeting point.
19
+
20
+ The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
21
+ ******************************************************************************************************/
22
+
23
+ #include " ../inc/ac.h"
24
+ class Solution
25
+ {
26
+ public:
27
+ int shortestDistance (vector<vector<int >> &grid)
28
+ {
29
+ // Calculate every building point to landing point distance, and get the minm.
30
+ int m = grid.size (), n = grid[0 ].size ();
31
+ vector<int > direction = {-1 , 0 , 1 , 0 , -1 }; // left up right down
32
+ auto total = grid;
33
+ int min_dist = 0 , walk = 0 ;
34
+ for (int i = 0 ; i < m; i++)
35
+ {
36
+ for (int j = 0 ; j < n; j++)
37
+ {
38
+ if (grid[i][j] == 1 )
39
+ {
40
+ min_dist = -1 ;
41
+ auto dist = grid;
42
+ queue<pair<int , int >> que;
43
+
44
+ que.emplace (i, j);
45
+
46
+ while (!que.empty ())
47
+ {
48
+ auto land = que.front ();
49
+ que.pop ();
50
+
51
+ for (int k = 0 ; k < 4 ; k++)
52
+ {
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])
56
+ {
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])
62
+ {
63
+ min_dist = total[x][y];
64
+ }
65
+ }
66
+ }
67
+ }
68
+ walk--;
69
+ }
70
+ }
71
+ }
72
+ return min_dist;
73
+ }
74
+ };
75
+
76
+ int main ()
77
+ {
78
+
79
+ vector<vector<int >> grid = {{1 , 0 , 2 , 0 , 1 }, {0 , 0 , 0 , 0 , 0 }, {0 , 0 , 1 , 0 , 0 }};
80
+ cout << Solution ().shortestDistance (grid) << " \n " ;
81
+ return 0 ;
82
+ }
0 commit comments