https://leetcode.com/problems/number-of-islands/
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
Problem Solving Ideas:
This problem and surrounded regions exactly the same, are the operation of the BFS of the map.
If the upper and lower is 1, go in that direction until the BFS is over. Once a BFS is an island.
This problem is more simple than surrounded regions, and there is no write-back operation.
The code is as follows
Public classSolution { Public intNumislands (Char[] grid) { if(Grid.length = = 0) { return0; } intresult = 0; //record the already traversed lattice int[] visited =New int[Grid.length] [Grid[0].length]; //the member of the queue is an array of {I,J}, recording the coordinates of this BFSqueue<int[]> queue =Newlinkedlist<int[]>(); for(inti = 0; i < grid.length; i++) { for(intj = 0; J < Grid[0].length; J + +) { if(Grid[i][j] = = ' 1 ' && visited[i][j] = = 0) {Queue.offer (New int[]{i, J}]; VISITED[I][J]= 1; //a while is a BFS, an island while(Queue.size () > 0) { int[] index =Queue.poll (); if(Index[0] > 0 && grid[index[0]-1][index[1] [= ' 1 ' && visited[index[0]-1][index[1]] = = 0) {Queue.offer (New int[]{index[0]-1, index[1]}); visited[index[0]-1][index[1]] = 1; } if(Index[1] > 0 && grid[index[0]][index[1]-1] = = ' 1 ' && visited[index[0]][index[1]-1] = = 0) {Queue.offer (New int[]{index[0], index[1]-1}); visited[index[0]][INDEX[1]-1] = 1; } if(Index[0] < grid.length-1 && Grid[index[0] + 1][index[1]] = = ' 1 ' && visited[index[0] + 1][index[1]] = = 0) {Queue.offer (New int[]{index[0] + 1, index[1]}); visited[index[0] + 1][index[1]] = 1; } if(Index[1] < grid[0].length-1 && Grid[index[0]][index[1] + 1] = = ' 1 ' && visited[index[0]][index[1] + 1 ] = = 0) {Queue.offer (New int[]{index[0], index[1] + 1}); visited[index[0]][INDEX[1] + 1] = 1; } } //once the BFS is over, the number of island +1result++; } } } returnresult; }}
Number of Islands