您的位置:首页 > 编程语言 > Java开发

[leetcode-200]Number of Islands(java)

2015-08-27 21:12 465 查看
问题描述:

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

分析:这道题主要考察DFS,维护一个栈,然后将相连的1全部遍历一遍之后,出栈,然后 count++;

代码如下:352ms

[code]public class Solution {
    class Node{
        int x;
        int y;
        public Node(int x,int y){
            this.x = x;
            this.y = y;
        }
    }
    public int numIslands(char[][] grid) {
        Stack<Node> stack = new Stack<>();

        int count = 0;
        int row = grid.length;
        if(row<=0)
            return 0;
        int col = grid[0].length;

        for(int i = 0;i<row;i++){
            for(int j = 0;j<col;j++){
                if(grid[i][j]=='1'){
                    stack.push(new Node(i,j));

                    while(!stack.isEmpty()){
                        Node top = stack.pop();
                        int x = top.x;
                        int y = top.y;
                        grid[x][y] = '0';

                        if(x+1<row && grid[x+1][y]=='1')
                            stack.push(new Node(x+1,y));
                        if(x-1>=0 && grid[x-1][y]=='1')
                            stack.push(new Node(x-1,y));
                        if(y+1<col && grid[x][y+1] == '1')
                            stack.push(new Node(x,y+1));
                        if(y-1>=0 && grid[x][y-1] == '1')
                            stack.push(new Node(x,y-1));
                    }
                    count++;
                }
            }
        }
        return count;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: