Given a 2d grid map ‘1‘
of S (land) ‘0‘
and S (water), count the number of islands. An island is surrounded by water and are formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the grid is all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer:1
Example 2:
11000
11000
00100
00011
Answer:3
Problem: Find out the number of block blocks in the matrix that are adjacent to each other and around 1.
belongs to the DFS idea.
Plug all 1 into a container, remove a 1 from the container, and take 1 of the adjacent walk out of the container as a single fetch. Repeat this until there is no element 1 in the container, and the number of occurrences is 1 of the area block block.
1unordered_map<string, pair<int,int>>Val_pos;2vector<vector<Char>>Thegrid;3 4 5 /**6 * Remove all land connecting with [I, K] adjecent horizontally or vertically. and the Pos.7 */8 voidRemoveland (intIintk) {9 TenTHEGRID[I][K] ='0'; One A stringstr = to_string (i) +"_"+to_string (k); - val_pos.erase (str); - the if(I-1>=0&& thegrid[i-1][k] = ='1'){ -Removeland (I-1, k); - } - + if(k +1< thegrid[0].size () && thegrid[i][k+1] =='1'){ -Removeland (i, K +1); + } A at if(i+1< Thegrid.size () && thegrid[i+1][k] = ='1'){ -Removeland (i+1, k); - } - - if(K-1>=0&& thegrid[i][k-1] =='1'){ -Removeland (i, K-1); in } - } to + intNumislands (vector<vector<Char>>&grid) { - the if(grid.size () = =0){ * return 0; $ }Panax Notoginseng -Thegrid =grid; the for(inti =0; I < grid.size (); i++){ + for(intK =0; K < grid[0].size (); k++){ A if(Grid[i][k] = ='1'){ the stringstr = to_string (i) +"_"+to_string (k); +VAL_POS[STR] ={i, k}; - } $ } $ } - - intres =0; the - while(Val_pos.size () >0 ){Wuyi inti = Val_pos.begin ()Second.first; the intK = Val_pos.begin ()Second.second; - Removeland (i, k); Wures++; - } About $ returnRes; -}
[Leetcode] 200. Number of Islands solving ideas