[LeetCode] Number of Islands

Source: Internet
Author: User

[LeetCode] Number of Islands

 

Given a 2d grid map'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


 

Mutual access between the bfs layer should be restrained.

 

Public class Solution {class Pair {int x, y; Pair (int x, int y) {this. x = x; this. y = y ;}} public int numIslands (char [] [] grid) {if (grid = null | grid. length = 0) return 0; int row = grid. length, column = grid [0]. length; int res = 0; for (int I = 0; I
 
  
Que = new Pair list <> (); que. offer (new Pair (I, j); while (! Que. isEmpty () {Pair p = que. poll (); grid [p. x] [p. y] = '*'; if (isIsland (grid, p. x-1, p. y) {// It is very important to prevent grid [p. x-1] [p. y] = '*'; que. offer (new Pair (p. x-1, p. y);} if (isIsland (grid, p. x + 1, p. y) {grid [p. x + 1] [p. y] = '*'; que. offer (new Pair (p. x + 1, p. y);} if (isIsland (grid, p. x, p. y-1) {grid [p. x] [p. y-1] = '*'; que. offer (new Pair (p. x, p. y-1);} if (isIsland (grid, p. x, p. y + 1) {grid [p. x] [p. y + 1] = '*'; que. offer (new Pair (p. x, p. y + 1) ;}} private boolean isIsland (char [] [] grid, int I, int j) {if (I <0 | I> = grid. length | j <0 | j> = grid [0]. length) return false; if (grid [I] [j] = '1') return true; return false ;}}
 
Dfs code is relatively simple, but the running time is slower than bfs

 

 

public class Solution {    public int numIslands(char[][] grid) {    if(grid==null||grid.length==0) return 0;    int row = grid.length,column = grid[0].length;    int res = 0;        for(int i=0;i
 
  =grid.length||j<0||j>=grid[0].length) return false;    if(grid[i][j]=='1') return true;    return false;    }}
 


 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.