zoukankan      html  css  js  c++  java
  • leetcode 200. Number of Islands 求岛的数量 ---------- java

    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

    求被0围起来的1的个数,连起来的1算一个

    每遇到一个1就把周围的1全部置为0;

    public class Solution {
        public int numIslands(char[][] grid) {
            
            int row = grid.length;
            if (row == 0){
                return 0;
            }
            int col = grid[0].length;
            if (col == 0){
                return 0;
            }
            int result = 0;
            for (int i = 0; i < row; i++){
                for (int j = 0; j < col; j++){
                    if (grid[i][j] == '1'){
                        setGrid(grid, i, j);
                        result++;
                    }
                }
            }
            return result;
        }
        
        public void setGrid(char[][] grid, int row, int col){
            
            if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length)
                return ;
            if (grid[row][col] == '1'){
                grid[row][col] = '0';
                setGrid(grid, row - 1, col);
                setGrid(grid, row + 1, col);
                setGrid(grid, row, col + 1);
                setGrid(grid, row, col - 1);
            }
        }
        
    }
  • 相关阅读:
    OCP-1Z0-053-V12.02-541题
    OCP-1Z0-053-V12.02-544题
    OCP-1Z0-053-V12.02-545题
    OCP-1Z0-053-V13.02-711题
    OCP-1Z0-053-V12.02-493题
    OCP-1Z0-053-V13.02-696题
    OCP-1Z0-053-V12.02-522题
    OCP-1Z0-053-V12.02-523题
    OCP-1Z0-053-V12.02-534题
    OCP-1Z0-053-V13.02-692题
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6611750.html
Copyright © 2011-2022 走看看