200. Number of Islands

来源:互联网 发布:protgresql和mysql 编辑:程序博客网 时间:2024/06/04 19:36

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.

Subscribe to see which companies asked this question

原来用DFS做的 现在感觉也许用BFS更好?

public class Solution {    private char[][] search(char[][] g,int i,int j){        if(i-1>=0&&g[i-1][j]=='1'){g[i-1][j]='2';        g=search(g,i-1,j);}        if(i+1<g.length&&g[i+1][j]=='1'){g[i+1][j]='2';        g=search(g,i+1,j);}        if(j-1>=0&&g[i][j-1]=='1'){g[i][j-1]='2';        g=search(g,i,j-1);}        if(j+1<g[0].length&&g[i][j+1]=='1'){g[i][j+1]='2';        g=search(g,i,j+1);}        return g;    }    private char[][] clean(char[][] g){        int a = g.length;        int b = g[0].length;        for(int i = 0;i<a;i++){            for(int j=0;j<b;j++){                if(g[i][j]=='2')g[i][j]='0';            }        }        return g;    }    public int numIslands(char[][] grid) {        if(grid.length==0)return 0;        if(grid[0].length==0)return 0;        // int hang = grid.length+2;        // int lie = grid[0].length+2;        // char [][] g = new char [hang][lie];        // for(int i = 1;i<hang-1;i++){        //     for(int j = 1;j<lie-1;j++){        //         g[i][j]=grid[i-1][j-1];        //     }        // }        int count = 0;        for(int i = 0;i<grid.length;i++){            for(int j =0;j<grid[0].length;j++){                if(grid[i][j]=='1'){grid[i][j]='2';                grid=search(grid,i,j);                // grid=clean(grid);                count++;}            }        }        return count;    }}

0 0
原创粉丝点击