LeetCode | 200. Number of islands

The original title ( Medium ):  

  Given a two-dimensional grid by a '1' (land) and '0' (water) composition, the number of islands is calculated. An island surrounded by water, and it is through the horizontal or vertical direction is connected to each adjacent land. You can assume that the water surrounding the four sides of the grid are.

  

 

 

Ideas: Recursive

  This type of question with a question we did before word search similar. So after I saw this question, I think of can be used with the same idea: Create an array representing the search direction in the current coordinates, if movement toward a certain direction grid is in line with certain conditions, go out into the direction a grid, and a recursive form of movement. Here the condition is not beyond the border, and there are islands available to move in that direction, and is not visited. If you try to complete all four directions, it can be returned. To prevent repeat visits has been visited island grid needs to access the array do a record. In the recursive process, each advancing a grid (qualifying only forward), it sets the grid has been accessed.

. 1  int XY [ . 4 ] [ . 4 ] = {{ . 1 , 0 }, { 0 , - . 1 }, {- . 1 , 0 }, { 0 , . 1 }};         // array representing the search direction is 
2  
. 3  void Helper ( Vector <Vector < int >> & Grid, int X, int Y, Vector <Vector < BOOL >> & visited)
 . 4  {
 . 5      visited [Y] [X] = to true ;
 . 6      for ( int I =0 ; I < . 4 ; I ++ )
 . 7      {
 . 8          // to the current grid start point, whether the mobile can attempt around it, can move continues recursively until the entire island is finished accessing 
. 9          int tempx + XY = X [I] [ 0 ];
 10          int tempY = Y + XY [I] [ . 1 ];
 . 11          // do not go beyond the border, and there are islands for the movement direction, and is unsubstituted visited 
12 is          IF (tempY> = 0 && tempY <grid.size () && tempx> = 0 && tempx <Grid [ 0 ] .size () && Grid [tempY] [tempx] &&! visited [tempY] [tempx])
 13 is              Helper (Grid, tempx, tempY, visited);
 14      }
 15  }
16 int numIslands(vector<vector<int>>& grid) {
17     vector<vector<bool>> visited(grid.size(), vector<bool>(grid[0].size(), false));
18 
19     int count = 0;
20 
21     for (int i = 0; i<grid.size(); i++)
22         for (int j = 0; j< grid[0].size(); j++)
23         {
24             if(! Grid [I] [J] && visited [I] [J])
 25              {
 26 is                  // main function: Find each island from the grid, if they find a land grid, will be accessed in the entire island recursion then they will not visit again look after the 
27                  Helper (Grid, i, J, visited);
 28                  // each come here to express discovered an island, counter +1 
29                  COUNT ++ ;
 30              }
 31          }
 32      return COUNT;
 33 }

Guess you like

Origin www.cnblogs.com/MisakiJH/p/11756266.html