4 条题解

  • 0
    @ 2025-5-25 12:24:31

    蒟蒻的题解,本题主要思路就是:遍历一遍地图,每次遇到了1就dfs把与他相邻的1以及它本身全都搞成0,同时计数器+1 ,这样遍历完一遍岛屿数量也就出来了!!

    //package TemplateQuestion;
    import javax.annotation.processing.SupportedSourceVersion;
    import java.io.*;
    public class Main{ //岛屿的数量   ,看到题目就知道是tmd  DFS了。。.
        static int n;
        static int [][]arr;
        static int count;
        static StreamTokenizer st;
        static PrintWriter pw;
        static int []mx={-1,1,0,0};
        static int []my={0,0,-1,1};
        static void dfs(int a,int b)
        {
            arr[a][b]=0;
          for(int i=0;i<4;i++)
          {
              int tx=a+mx[i];
              int ty=b+my[i];
              if(tx<1||tx>n||ty<1||ty>n||arr[tx][ty]==0)
              {
                  continue;
              }
              dfs(tx,ty);
          }
        }
       public static void main(String[] args) throws IOException {
            st=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
            pw=new PrintWriter(System.out);
            count=0;
            st.nextToken();
            n= (int) st.nval;
            arr=new int[n+1][n+1];
            for(int i=1;i<=n;i++)
            {
                for(int j=1;j<=n;j++)
                {
                    st.nextToken();
                    arr[i][j]= (int) st.nval;
                }
            }
            for(int i=1;i<=n;i++)
            {
                for(int j=1;j<=n;j++)
                {
                    if(arr[i][j]==1)
                    {
                        count++;
                        dfs(i,j);
                    }
                }
            }
            System.out.println(count);
        }
    }
    
    

    信息

    ID
    33
    时间
    1000ms
    内存
    256MiB
    难度
    3
    标签
    递交数
    33
    已通过
    19
    上传者