[Locked] Walls and Gates

Source: Internet
Author: User

Walls and Gates 

You is given a m x n 2D grid initialized with these three possible values.

    1. -1-A wall or an obstacle.
    2. 0-Gate A.
    3. INF-Infinity means a empty room. We use the value of represent as assume that the 231 - 1 = 2147483647 distance to INF a gate are less than 2147483647 .

Fill each empty and the distance to its nearest gate. If It is the impossible to reach a gate, it should are filled with INF .

For example, given the 2D grid:

INF  -1  0  infinf inf inf  -1inf  -1 inf  -1  0  -1 inf INF

After running your function, the 2D grid should is:

  3  -1   0   1  2   2   1  -1  1  -1   2  -1  0  -1   3   4

Analysis:

Deep search Dfs, attention pruning, note overflow

Code:

//Deep Search, three cases return: the room number has been smaller than the current distance, walls and doors, accessed, and these three cases can be expressed in a formula Grids[i][j] < distvoidDFS (vector<vector<int> > &grids,intDistintIintj) {if(Grids[i][j] <Dist)return; GRIDS[I][J]=Dist; DFS (grids, dist+1, I, J +1); DFS (grids, dist+1, i +1, J); DFS (grids, dist+1, I, J-1); DFS (grids, dist+1I1, J); return;}voidDistancefromgate (vector<vector<int> > &grids) {    if(Grids.empty ())return; //set up a border sentryGrids.insert (Grids.begin (), vector<int> (grids[0].size (),-1)); Grids.push_back (Vector<int> (grids[0].size (),-1));  for(Auto &row:grids) {Row.insert (Row.begin (),-1); Row.push_back (-1); }    //recursion starting from every 0     for(inti =0; I < grids.size (); i++)         for(intj =0; J < grids[0].size (); J + +)            if(Grids[i][j] = =0) DFS (grids,0, I, J); //Remove Border Sentrygrids.erase (Grids.begin ());    Grids.pop_back ();  for(Auto &row:grids)        {Row.erase (Row.begin ());    Row.pop_back (); }    return;}

[Locked] Walls and Gates

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.