Leetcode 200. Number of Islands

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值