• 【leetcode】200. Number of Islands


    原题:

    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'的时候,递归的把这个'1'及其周围的'1'都变成'0',这样就相当于消灭了一个island。于是乎有了下面的代码,其实还是很简单的哈,但是这个转换实在是没想到,以后要记住。

    代码:

    public class Solution {
        public int numIslands(char[][] grid) {
            int ret = 0;
            for(int i=0;i<grid.length;i++) {
                for(int j=0;j<grid[0].length;j++) {
                    if(grid[i][j] == '1') {
                       dfs(grid, i, j);
                        ret++; 
                    }
                    
                }
            }
            return ret;
        }
        
        void dfs(char[][] grid, int i, int j) {
            if(i<0 || i>= grid.length || j<0 || j>=grid[0].length || grid[i][j] != '1') return;
            grid[i][j] = '0';
            dfs(grid, i-1, j);
            dfs(grid, i+1, j);
            dfs(grid, i, j-1);
            dfs(grid, i, j+1);
        }
    }
  • 相关阅读:
    .ellipsis 超过的部分显示省略号
    js 里面上一页和下一页
    CSS让你的IE浏览器崩溃(Crash your IE)作者:雪候鸟 来源: 风雪之隅
    元素居中显示
    jquery Carousel
    tabs 选择加载
    弹出窗
    下拉广告`
    opacity
    小波分析实验: 实验1 连续小波变换
  • 原文地址:https://www.cnblogs.com/puyangsky/p/5879907.html
Copyright © 2020-2023  润新知