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);
                }
            }
        }
    }
  • 相关阅读:
    秒杀应用的MySQL数据库优化
    mongodb三种存储引擎高并发更新性能专题测试
    一次项目实践中DBCP数据库连接池性能优化
    初识中间件之消息队列
    Android性能测试--内存
    JVM源码分析之栈溢出完全解读
    case when then end
    工厂模式
    单例模式
    隐藏响应的server,X-Powered-By
  • 原文地址:https://www.cnblogs.com/hwu2014/p/4524382.html
Copyright © 2011-2022 走看看