• 200. Number of Islands 200.岛屿数(可以形状一样)


    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:

    Input: grid = [
      ["1","1","1","1","0"],
      ["1","1","0","1","0"],
      ["1","1","0","0","0"],
      ["0","0","0","0","0"]
    ]
    Output: 1
    

    Example 2:

    Input: grid = [
      ["1","1","0","0","0"],
      ["1","1","0","0","0"],
      ["0","0","1","0","0"],
      ["0","0","0","1","1"]
    ]
    Output: 3

    思路:不知道递归过程中怎么数数,应该在主函数里面写啊。

    class Solution {
        public int numIslands(char[][] grid) {
            //cc
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int count = 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);
                        count++;
                    }
                }
            }
            
            return count;
        }
        
        //返回面积
        public int dfs(char[][] grid, int x, int y) {
            //标记
            if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
               grid[x][y] == '1') {             
                    grid[x][y] = '0';
                                  
                    dfs(grid, x - 1, y); 
                    dfs(grid, x + 1, y);
                    dfs(grid, x, y - 1);
                    dfs(grid, x, y + 1);         
            }
            
            return 0;
        }
    }
    View Code


  • 相关阅读:
    最长连续子序列(dp,分而治之递归)
    判断线段是否相交
    1840: Jack Straws
    5065: 最长连续子序列
    TZOJ 4493: Remove Digits
    TZOJ 5271: 质因数的个数
    2019年天梯赛
    PTA 树的遍历
    TZOJ:3660: 家庭关系
    PTA 复数四则运算
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13569930.html
Copyright © 2020-2023  润新知