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
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
Idea: The width-first algorithm, which encounters ' 1 ' without being accessed, is the number of islands + +, while the island all ' 1 ' is marked as visited.
public class Solution {linkedlist<int[]> q = new linkedlist<> (); public int numislands (char[][] grid) {if (grid==null) {return 0; } int m=grid.length; if (m==0) {return 0; } int n=grid[0].length; Boolean[][] visited = new boolean[m][n];//mark (I,J) has been accessed, here only mark ' 1 ', do not mark ' 0 ' int cnt=0;//statistics Island number for (int i=0; i<m;i++) {for (int j=0;j<n;j++) {if (grid[i][j]== ' 1 ' &&visited[i][j]==false) {//Found new I Sland BFS (GRID,VISITED,I,J);//Mark All ' 1 ' (that is, traversing the entire island) from where ' 1 ' can reach the cnt++; }}} return cnt; } private void BFs (char[][] grid, boolean[][] visited,int x,int y) {fill (grid,visited,x,y);//first mark (x, y), then mark (x, y) Lower left and right while (!q.isempty ()) {int[] Point=q.poll (); int i=point[0]; int j=point[1]; Fill (grid,visited,i+1,j); Fill (grid,visited,i-1,J); Fill (grid,visited,i,j+1); Fill (grid,visited,i,j-1); }} private void Fill (char[][] grid, boolean[][] Visited,int I,int j) {if (i<0| | i>=grid.length| | j<0| | j>=grid[0].length| | grid[i][j]!= ' 1 ' | | Visited[i][j]==true) {return; } visited[i][j]=true; Q.add (New int[]{i,j}); } }
Number of Islands