Description:
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
Code:
1 #defineMAX 5002 3 structVertex4 {5 intRow;6 intCol;7VertexintXinty): Row (x), col (y) {8 }9 };Ten One classSolution { A Private: - BOOLVisit[max][max]; - Public: the - voidBfstraverse (vector<vector<Char>>& Grid,intIintj) - { -VISIT[I][J] =true; +Deque<vertex>m; - M.push_back (Vertex (i,j)); + while(!m.empty ()) A { atVertex v =M.front (); - M.pop_front (); - intMrow =V.row; - intMCol =V.col; - for(intK =1; K <=4; ++k) - { in Switch(k) - { to Case 1: +Mrow = v.row-1; -MCol =V.col; the Break; * Case 2: $Mrow = v.row+1;Panax NotoginsengMCol =V.col; - Break; the Case 3: +Mrow =V.row; AMCol = v.col-1; the Break; + Case 4: -Mrow =V.row; $MCol = v.col+1; $ Break; - } - if(Mrow >=0&& Mrow < Grid.size () && MCol >=0&& MCol < grid[0].size () the&& Grid[mrow][mcol] = ='1'&& Visit[mrow][mcol] = =false) - {WuyiVisit[mrow][mcol] =true; the M.push_back (Vertex (mrow,mcol)); - } Wu } - } About } $ - intNumislands (vector<vector<Char>>&grid) { -size_t row =grid.size (); - if(Row = =0) A return 0; +size_t col = grid[0].size (); the //Note that the initialization of two-dimensional arrays can not be used directly with Visit[max][max] = {false}, should take A For loop (memset function seems to be possible) - for(inti =0; i < row; ++i) $ { the for(intj =0; J < Col; ++j) theVISIT[I][J] =false; the } the intresult =0; - for(inti =0; i < row; ++i) in { the for(intj =0; J < Col; ++j) the { About if(grid[i][j]=='1'&& Visit[i][j] = =false ) the { the++result; the bfstraverse (Grid, I, j); + } - } the }Bayi returnresult; the } the};
View Code
Number of Islands