How to use C++ or Go to calculate the number of islands in a matrix
This article introduces the knowledge of "how to use C++ or Go to find the number of islands in the matrix". Many people will encounter this dilemma in the operation of practical cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Catalogue
1. C++ implementation
2. Go language implementation
Give you a two-dimensional grid consisting of'1' (land) and'0' (water). Please calculate the number of islands in the grid.
Islands are always surrounded by water, and each island can only be formed by adjacent land connections horizontally and / or vertically. In addition, you can assume that all four sides of the mesh are surrounded by water.
Example 1:
Enter:
Grid = [
["1", "1", "1", "0"]
["1", "1", "0", "1", "0"]
["1", "1", "0", "0", "0"]
["0", "0", "0", "0"]
]
Output:
one
Example 2:
Enter:
Grid = [
["1", "1", "0", "0", "0"]
["1", "1", "0", "0", "0"]
["0", "0", "1", "0", "0"]
["0", "0", "0", "1", "1"]
]
Output:
three
Tip:
M = = grid.length
N = = grid [I] .length
1 = 0) & (c < (int) grid [0] .size ()); return bRow & & bCol } / / void dfs (int [] [] grid, int rpenint c) {void dfs (vector& grid, int rpenint c) {/ / judge base case / / if the coordinates (rMaginc) are out of the grid range, directly return if (! inArea (grid,r,c)) {return } / / if it is not an island, return directly to if (grid [r] [c]! ='1') {return;} / / change the original "1" to "0" grid [r] [c] = '2islands; / / visit the upper, lower, left and right four adjacent nodes dfs (grid, r-1, c) Dfs (grid, r + 1, c); dfs (grid, r, Cmurl); dfs (grid, r, cymen1);} / / find the number of islands / / time complexity: O (MN) O (MN), where MM and NN are rows and columns, respectively. / / Space complexity: O (MN) O (MN). In the worst case, the whole grid is land, and the depth of depth-first search reaches MN. / / int numIslands (vector& grid) {int r = grid.size (); if (! r) return 0; int c = grid [0] .size (); int num = 0; for (int I = 0; I < r; iTunes +) {for (int j = 0; j < c) ) {if (grid [I] [j] = ='1') {+ + num; dfs (grid, I, j);} return num } int main () {/ / Island / / 11 / / 0 10 / / 100 / / 101 vector row1; row1.push_back ('1'); vector row2; row2.push_back ('0') Row2.push_back ('1'); row2.push_back ('0'); vector row3; row3.push_back ('1'); row3.push_back ('0'); row3.push_back ('0'); vector row4; row4.push_back ('1'); row4.push_back ('0') Row4.push_back ('1'); vector grid; grid.push_back (row1); grid.push_back (row2); grid.push_back (row3); grid.push_back (row4); int numLands = numIslands (grid); cout