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);
                }
            }
        }
    }
  • 相关阅读:
    微信小程序与用户交互
    洛谷P2066 机器分配
    巴蜀3540 -- 【Violet 6 最终话】蒲公英
    POJ1984 Navigation Nightmare
    洛谷P1387 最大正方形
    洛谷P2679 子串
    洛谷P2057 善意的投票
    Bzoj 2726 SDOI 任务安排
    POJ2761 Feed the dogs
    P1272 重建道路
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4524382.html
Copyright © 2011-2022 走看看