Leetcode 200. Number of Islands
Given a 2d grid map of '1'
s (land) and '0'
s (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Analysis:This is quite similar to the problem I have met before in the computer vision course that to count the number of the objects in a picture.
And For this problem We can use the DFS and BFS method. DFS is quite simple. just to write the recursive method to loop for the whole value, and a important method to use is to use a two dimension array to reduce the number of implementation of the method.
Code
public class Solution {
public int numIslands(char[][] grid) {
int rowNum = grid.length;
if(rowNum == 0)
return 0;
int colNum = grid[0].length;
if(colNum == 0)
return 0;
int [][] record = new int[rowNum][colNum];
int number = 0;
for(int i = 0; i < rowNum; i++){
for(int j = 0; j < colNum ; j++){
if(grid[i][j] != '1')
record[i][j] = 0;
if(grid[i][j] == '1' && record[i][j] == -1){
num++;
dfsdfs(grid, record, number, row, col);
}
}
}
return number;
}
public void dfs(char[][]grid, int[][]record, int number, int row, int col)
{
int rowNum = grid.length;
int colNum = grid[0].length;
record[row][col] = number;
// if(row < 0 || row >= rowNum)
// return;
//
// if(col < 0 || row >= colNum)
// return;
//
// if(grid[row][col] != '1')
// record[row][col] = 0;
// else if(record[i][j] != -1)
// return;
if(row - 1 >= 0 && grid[row - 1][col] == '1' || record[row - 1][col] == -1)
dfs(grid, record, number, row - 1, col);
if(row + 1 < rowNum && grid[row + 1][col] == '1' || record[row + 1][col] == -1)
dfs(grid, record, number, row + 1, col);
if(col - 1 >= 0 && grid[row][col - 1] == '1' || record[row][col - 1] == -1)
dfs(grid, record, number, row, col - 1);
if(col + 1 < colNum && grid[row][col + 1] == '1' || record[row][col + 1] == -1)
dfs(grid, record, number, row, col + 1);
}
}
Another method is BFS, here is the method to use BFS, http://blog.csdn.net/guorudi/article/details/44997949
Use queue to store the pair which is a class for the x and y position value, and use BFS to recursivlly visit every element.