counted on some islands. An island, surrounded by water, is formed by connecting the adjacent land laterally or vertically. You can assume that all four sides of the grid are surrounded by water.
1. Check if it has been accessed, if it is set to X, then take it to the next grid.
2. Check whether it is 1, if not, set it to an already visited, X.
3. Find 1 of each island, and then increase the number of islands Numisland,
Go to the beginning of each 1, set it to have been visited, that is set to X
4. Return to Numisland.
The time complexity is N, when n is the size of the matrix
The spatial complexity is 1 because we reuse the matrix as a visited list.
1 Public classSolution {2 3 Private voidDiscoverisland (Char[] g,intHintWintXinty)4 {5 if(X < 0 | | Y < 0 | | x >= H | | y >= w)return;6 7 if(G[x][y] = = ' X ' | | g[x][y] = = ' 0 ')return;8 9G[x][y] = ' x ';Ten OneDiscoverisland (g,h,w,x+1, y); ADiscoverisland (g,h,w,x,y+1); -Discoverisland (g,h,w,x-1, y); -Discoverisland (g,h,w,x,y-1); the } - - Public intNumislands (Char[] grid) { - + if(Grid.length = = 0)return0; - + intNumislands = 0; A introws =grid.length; at intcols = grid[0].length; - for(inti=0; i<rows; i++ ) - { - for(intj=0; j<cols; J + + ) - { - if(Grid[i][j] = = ' x ')Continue; in - if(Grid[i][j] = = ' 1 ' ) to { + Discoverisland (grid, rows, cols, I, j); -numislands++; the } * Else $ {Panax NotoginsengGRID[I][J] = ' x '; - } the } + } A the returnnumislands; + } - $}
public class Solution {void Findisland (char[][] grid, int x, int y, hashset<integer> used) {int tag = 0; int rows = Grid.length; int columns = Grid[0].length; Up if (x > 0 && grid[x-1][y] = = ' 1 ') {tag = (x-1) * columns + y; if (!used.contains (tag)) {Used.add (tag); Findisland (grid, x-1, y, used); }}//Right if (Y < (columns-1) && grid[x][y + 1] = = ' 1 ') {tag = x * Colum NS + y + 1; if (!used.contains (tag)) {Used.add (tag); Findisland (grid, x, Y + 1, used); }}//Down if (x < (rows-1) && grid[x + 1][y] = = ' 1 ') {tag = (x + 1) * Colu MNS + y; if (!used.contains (tag)) {Used.add (tag); Findisland (grid, X + 1, y, used); }}//left if (Y > 0 &&Amp Grid[x][y-1] = = ' 1 ') {tag = x * columns + y-1; if (!used.contains (tag)) {Used.add (tag); Findisland (grid, X, y-1, used); }}}} public int numislands (char[][] grid) {if (Grid = = NULL | | grid.length = = 0) {return 0; } int result = 0; int rows = Grid.length; int columns = Grid[0].length; Hashset<integer> used = new hashset<integer> (); for (int i = 0, i < rows; ++i) {for (int j = 0; j < columns; ++j) {if (grid[i][j] = = ' 1 ' ) {int tag = i * columns + j; if (!used.contains (tag)) {Used.add (tag); Result + +; Findisland (Grid, I, j, used); }}}} return result; }}
A 01-point plot, counting the number of islands.