• LeetCode-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

    Credits:
    Special thanks to @mithmatt for adding this problem and creating all test cases.

    Solution:

    Just BFS.

     1 public class Solution {
     2     int[][] moves = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
     3     
     4     public int numIslands(char[][] grid) {
     5         if (grid.length==0 || grid[0].length==0) return 0;
     6         int count = 0;
     7 
     8         for (int i=0;i<grid.length;i++)
     9             for (int j=0;j<grid[0].length;j++)
    10                 if (grid[i][j] == '1'){
    11                     count++;
    12                     markOneIsland(grid,new int[]{i,j});
    13                 }
    14 
    15         return count;
    16     }
    17     
    18     public void markOneIsland(char[][] grid, int[] start){
    19         Deque<int[]> pointList = new LinkedList<int[]>();
    20         pointList.add(start);        
    21 
    22         while (!pointList.isEmpty()){
    23             int[] head = pointList.poll();
    24             for (int i=0;i<4;i++){
    25                 int[] next = new int[]{head[0]+moves[i][0],head[1]+moves[i][1]};            
    26                 if (next[0]>=0 && next[0]<grid.length && next[1]>=0 && next[1]<grid[0].length && grid[next[0]][next[1]] == '1'){
    27                     pointList.add(next);
    28                     grid[next[0]][next[1]] = '2';
    29                 }
    30             }
    31         }
    32     }
    33 }
  • 相关阅读:
    使用vs2010编译 Python SIP PyQt4
    谷歌编程指南
    【转】微策略面经相关资料
    KMP 算法
    C++ 拷贝构造函数
    虚继承 虚表 定义一个不能被继承的类
    cache的工作原理
    背包问题
    【转】C/C++ 内存对齐
    【转】 Linux/Unix 进程间通信的各种方式及其比较
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5772488.html
Copyright © 2020-2023  润新知