zoukankan      html  css  js  c++  java
  • 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.

      假设给了2维的网格图(包含“0”和“1”,1代表陆地,0代表水),计算出有多少岛。岛被水围绕并陆地在垂直或者水平方向连接,假设网格的四边被水围绕。

    【分析】

      1. 设置一个辅助的二维数组boolean visited[][],用于记录当前点是否访问过,false代表没访问过,true代表访问过

      2. 采用DFS的方式

    【算法实现】

    public class Solution {
        public int numIslands(char[][] grid) {
            if(grid==null || grid.length==0)
                return 0;
            boolean[][] visited = new boolean[grid.length][grid[0].length];
            int res=0;
            for(int i=0; i<grid.length; i++) {
                for(int j=0; j<grid[0].length; j++) {
                    if(grid[i][j]=='1' && !visited[i][j]) {
                        System.out.println("i:"+i+",j:"+j);
                        res++;
                        visited[i][j]=true;
                        randomMove(grid,i,j,visited);
                    }
                }
             }
            return res;
        }
        
        public static void randomMove(char[][] grid,int x,int y,boolean[][] visited) {
            int rows = grid.length;
            int cols = grid[0].length;
            int[][] pos = {{0,1},{0,-1},{-1,0},{1,0}};
            for(int i=0; i<4; i++) {
                int xx = x+pos[i][0];
                int yy = y+pos[i][1];
                if(xx>=0 && xx<rows && yy>=0 && yy<cols && !visited[xx][yy] && grid[xx][yy]=='1') {
                    visited[xx][yy] = true;
                    randomMove(grid , xx , yy , visited);
                }
            }
        }
    }
  • 相关阅读:
    阿里云短信支付微信支付
    python 阿里云短信群发推送
    python twilio 短信群发 知识留存
    python爬虫 发送定时气象预报
    python beautifulsoup爬虫
    strongswan
    Docker进入主流,PaaS大有可为(转)
    Python 网页爬虫 & 文本处理 & 科学计算 & 机器学习 & 数据挖掘兵器谱(转)
    在IT网站上少花些时间
    Python 代码性能优化技巧(转)
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4524382.html
Copyright © 2011-2022 走看看