leetcode--Number of Islands

来源:互联网 发布:淘宝邮票真假怎么鉴定 编辑:程序博客网 时间:2024/06/05 14:47

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:

11110110101100000000

Answer: 1

Example 2:

11000110000010000011

Answer: 3

[java] view plain copy
  1. public class Solution {  
  2.     public int numIslands(char[][] grid) {  
  3.         int res = 0;  
  4.         int rows = grid.length;  
  5.         if(rows==0return res;  
  6.         int cols = grid[0].length;  
  7.         if(cols==0return res;  
  8.         int[] xdir = new int[]{1,-1,0,0};  
  9.         int[] ydir = new int[]{0,0,1,-1};  
  10.         ArrayList<Integer> queue_x = new ArrayList<Integer>();  
  11.         ArrayList<Integer> queue_y = new ArrayList<Integer>();  
  12.           
  13.         for(int i=0;i<rows;i++){  
  14.             for(int j=0;j<cols;j++){  
  15.                 if(grid[i][j]=='1'){  
  16.                     res++;  
  17.                     queue_x.add(i);queue_y.add(j);  
  18.                     int low = 0;  
  19.                     int high = 1;  
  20.                     while(low<high){  
  21.                         for(int k=0;k<4;k++){  
  22.                             int x = queue_x.get(low)+xdir[k];  
  23.                             int y = queue_y.get(low)+ydir[k];  
  24.                             if(x>=0&&x<rows&&y>=0&&y<cols){  
  25.                                 if(grid[x][y]=='1'){  
  26.                                     grid[x][y]='0';  
  27.                                     queue_x.add(x);  
  28.                                     queue_y.add(y);  
  29.                                     high++;  
  30.                                 }  
  31.                             }  
  32.                         }  
  33.                         low++;  
  34.                     }  
  35.                     queue_x.clear();queue_y.clear();  
  36.                 }  
  37.             }  
  38.         }  
  39.         return res;  
  40.     }  
  41. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46574435

原创粉丝点击