[LeetCode] Number of Islands 岛屿的数量

37 篇文章 0 订阅
22 篇文章 0 订阅

测试数据:

图形化表示:

 

代码:

public class liubobo_8_5 {
    /// 200. Number of Islands
/// https://leetcode.com/problems/number-of-islands/description/
/// 时间复杂度: O(n*m)
/// 空间复杂度: O(n*m)
        private int d[][] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        private int m, n;
        private boolean visited[][];

        public int numIslands(char[][] grid) {

            if(grid == null || grid.length == 0 || grid[0].length == 0)
                return 0;

            m = grid.length;
            n = grid[0].length;

            visited = new boolean[m][n];

            int res = 0;//记录岛屿的个数
            for(int i = 0 ; i < m ; i ++)
                for(int j = 0 ; j < n ; j ++)
                    if(grid[i][j] == '1' && !visited[i][j]){//=="1"代表是陆地
                        dfs(grid, i, j);
                        res ++;
                    }

            return res;
        }

        // 从grid[x][y]的位置开始,进行floodfill
        // 保证(x,y)合法,且grid[x][y]是没有被访问过的陆地
        private void dfs(char[][] grid, int x, int y){

            //assert(inArea(x,y));
            visited[x][y] = true;
            //深度优先遍历,注意这里的递归终止条件已经被融入到下面的if中了
            for(int i = 0; i < 4; i ++){
                int newx = x + d[i][0];
                int newy = y + d[i][1];
                if(inArea(newx, newy) && !visited[newx][newy] && grid[newx][newy] == '1')
                    dfs(grid, newx, newy);
            }

            return;
        }

        private boolean inArea(int x, int y){
            return x >= 0 && x < m && y >= 0 && y < n;
        }

        public static void main(String[] args) {

            char grid1[][] = {
                    {'1','1','1','1','0'},
                    {'1','1','0','1','0'},
                    {'1','1','0','0','0'},
                    {'0','0','0','0','0'}
            };
            System.out.println((new liubobo_8_5()).numIslands(grid1));
            // 1

            // ---

            char grid2[][] = {
                    {'1','1','0','0','0'},
                    {'1','1','0','0','0'},
                    {'0','0','1','0','0'},
                    {'0','0','0','1','1'}
            };
            System.out.println((new liubobo_8_5()).numIslands(grid2));
            //
        }

}

 

类似问题:

1. 130Surrounded Regions

2. 417Pacific Atlantic Water Flow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值