zoukankan      html  css  js  c++  java
  • 小岛问题

    问题描述:

    一个只包含0和1的阵列,找到1的组的个数,每个组的定义是横向和纵向相邻的值都为1,如图中一共有4个组,用不同颜色的框分割(可以参见不同粗细勾画起来的框)。
    package test;
    
    public class Islands {
        public static int countIslands(int[][] m){
            if(m==null||m[0]==null)
                return 0;
            int N = m.length;
            int M = m[0].length;
            int res = 0;
            for(int i = 0;i<N;i++)
                for(int j=0;j<M;j++){
                    if(m[i][j]==1){
                        res++;
                        infect(m,i,j,N,M);
                    }
                        
                }
            return res;
        }
        public static void infect(int[][] m,int i,int j,int N,int M){
            if(i<0||i>=N||j<0||j<=M||m[i][j]!=1)
                return;
            m[i][j]=2;
            infect(m,i+1,j,N,M);
            infect(m,i-1,j,N,M);
            infect(m,i,j+1,N,M);
            infect(m,i,j-1,N,M);
        }
        public static void main(String[] args) {
            int[][] m1 = {  { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
                            { 0, 1, 1, 1, 0, 1, 1, 1, 0 }, 
                            { 0, 1, 1, 1, 0, 0, 0, 1, 0 },
                            { 0, 1, 1, 0, 0, 0, 0, 0, 0 }, 
                            { 0, 0, 0, 0, 0, 1, 1, 0, 0 }, 
                            { 0, 0, 0, 0, 1, 1, 1, 0, 0 },
                            { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };
            System.out.println(countIslands(m1));
    
            int[][] m2 = {  { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 
                            { 0, 1, 1, 1, 1, 1, 1, 1, 0 }, 
                            { 0, 1, 1, 1, 0, 0, 0, 1, 0 },
                            { 0, 1, 1, 0, 0, 0, 1, 1, 0 }, 
                            { 0, 0, 0, 0, 0, 1, 1, 0, 0 }, 
                            { 0, 0, 0, 0, 1, 1, 1, 0, 0 },
                            { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, };
            System.out.println(countIslands(m2));
    
        }
    }
  • 相关阅读:
    899. Orderly Queue
    856. Score of Parentheses
    833. Find And Replace in String
    816. Ambiguous Coordinates
    770. Basic Calculator IV
    冒泡排序(Bubble Sort)
    C
    B
    A
    HDOJ-1391
  • 原文地址:https://www.cnblogs.com/xiaoxli/p/9560995.html
Copyright © 2011-2022 走看看