[LeetCode317] Shortest Distance from all buildings

Source: Internet
Author: User
You want to build a house on an empty land which reaches all buildings in the shortest amount of distance.
You is given a 2D grid of values 0, 1 or 2, Where:each 0 marks an empty land which you can pass by freely.
Each of the 1 marks a building which you cannot pass through.
Each 2 marks a obstacle which you cannot pass through. The distance is calculated using Manhattan distance, where distance (P1, p2) = |p2.x-p1.x|

+ |p2.y-p1.y|.   For example, given three buildings at (0,0), (0,4), (2,2), and a obstacle at (0,2): 1-0-2-0-1 |   |   |   |
    |   0-0-0-0-0 |   |   |   |
    | 0-0-1-0-0 The point (on) is an ideal empty land to build a house, as the total travel distance of 3+3+1=7 is mini Mal.

So return 7. Note:there'll is at least one building.

If It isn't possible to build such house according to the above rules, return-1. Hide company Tags Google zenefits Hide Tags breadth-first Search Hide Similar problems (M) Walls and Gates (H) BestMeeting Point
 

Discuss:

Https://leetcode.com/discuss/questions/oj/shortest-distance-from-all-buildings

The problem will be known to use BFS at a glance. But there are a lot of details: for example, the last point to find must be all the building can reach, so if it is:

{* *}
{0,1}

This situation should be return-1;

We traverse the entire grid and start BFS once we find 1. For the first building (which is grid[i][j] = = 1) It can reach the point where it is all 0, and once it visited over these points, we update it to-1. For the second building, we can only walk those 1 points, for what. Because if the first point cannot reach a certain point P, then this p has not satisfied the topic requirement: You want to build a house on an empty land which reaches *all* buildings in the shortest Amount of distance. We don't need to check this point. So eventually we traverse total this matrix not only to skip those total[i][j] = = 0 points (because these points are building or obstacle locations), and we'll skip total[i][j]! = Canachieve points (because these points cannot be reached by all building, in fact canachieve this variable records a total of how many building).

To clarify these ideas, you can write the following code,40ms:

Class Solution {Public:int shortestdistance (vector<vector<int>>& grid) {if (Grid.empty ()) re
        turn-1;
        int m = grid.size (), n = grid[0].size (); Vector<vector<int>> Total (m,vector<int> (n,0));//using Vector to store information
        Distance for each possible node.
        Vector<vector<int>> Newgrid = grid;//we dont want to change original matrix;
        int canachieve = 0, mindist = Int_max;
        Vector<pair<int, int>> dirs = {{0,1}, {1,0}, {0,-1}, { -1,0}};
                    for (int i = 0; i<m; ++i) {for (int j = 0; j<n; ++j) {if (grid[i][j] = = 1) {
                    Queue<pair<int, int>> Q;
                    Q.push (Make_pair (I,J));//current 1 position, we start BFS;
                    Vector<vector<int>> Dist (m,vector<int> (n,0));
       Using dist to store distance information start from the current building.             while (!q.empty ()) {Auto cur = q.front ();
                        Q.pop ();
                            for (auto d:dirs) {int newx = Cur.first+d.first, newy = Cur.second+d.second;  if (newx<m && newx>=0 && newy<n && newy >=0 && Newgrid[newx][newy]
                                = = Canachieve) {--newgrid[newx][newy];
                                Dist[newx][newy] = dist[cur.first][cur.second]+1;
                                Total[newx][newy] + = Dist[newx][newy];
                            Q.push (Make_pair (newx, newy));  }}}--canachieve;//after each update and we change the node
                We can achieve by--canachieve. }}} for (int i = 0; I<total.size (), ++i) {for (int j = 0; J<total[0].size () ;
    ++J) {            if (Total[i][j] && newgrid[i][j] = = canachieve) mindist = min (mindist, total[i][j]);//Insure All Build
            ING can achieve this point!; }} return mindist = = Int_max?
    -1:mindist;
 }
};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.