original title link:https://leetcode.com/problems/number-of-islands/
Test Instructions 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
Exercises
The main idea of the problem is to find a map of the Unicom region, a unicom sub-map is considered an island. It is obvious that every point that has not been visited and is land is searched up and down, so that a unicom sub-map can be found. Then do this all over the whole map, and you'll find all the results. The code is as follows:
1 Public classSolution {2 Public Static BooleanFlag =false;3 4 Public intNumislands (Char[] grid) {5 Boolean[] visited =New Boolean[grid.length][];6 for(inti = 0; i < grid.length; i++)7Visited[i] =New Boolean[grid[i].length];8 for(inti = 0; i < grid.length; i++) {9 for(intj = 0; J < Grid[0].length; J + +) {TenVISITED[I][J] =false; One } A } - intres = 0; - for(inti = 0; i < grid.length; i++) { the for(intj = 0; J < Grid[0].length; J + +) { -Flag =false; - process (I, J, grid, visited); - if(flag) +res++; - } + } A returnRes; at } - - Public voidProcessintIintJChar[] Grid,Boolean[] visited) { - if(grid[i][j]! = ' 1 ' | |Visited[i][j]) - return; -VISITED[I][J] =true; inFlag =true; - if(J >= 1) toProcess (I, j-1, grid, visited); + if(I >= 1) -Process (i-1, J, Grid, visited); the if(i+1<grid.length) *Process (i + 1, J, Grid, visited); $ if(j+1<grid[0].length)Panax NotoginsengProcess (I, j + 1, grid, visited); - } the}
[Leetcode] Number of Islands