[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; }}