4 条题解
-
0
JAVA ac代码:
package abcd; import java.util.*; import java.util.StringTokenizer; import java.io.*; public class Main { static int n; static int[][] a;//矩阵 static int ans=0;//答案 static int[] dx= {0,0,-1,1}; static int[] dy= {1,-1,0,0}; public static void main(String[] args) { n=in.nextInt(); a=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { a[i][j]=in.nextInt(); } } //遍历图 for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { //当这个点是陆地 if(a[i][j]==1) { ans++;//岛屿数+1 bfs(i,j);//将相连的陆地全部设置为0 } } } out.println(ans); out.close(); } private static void bfs(int i, int j) { Queue<int[]> q=new LinkedList<>(); q.add(new int[]{i,j});//将当前点入队 //遍历直到周围都是0 while(!q.isEmpty()) { //获得当前相连陆地点的坐标 int[] temp=q.poll(); int x=temp[0]; int y=temp[1]; //枚举这个坐标上下左右四个点 for(int k=0;k<4;k++) { int x1=x+dx[k]; int y1=y+dy[k]; //越界分析和是海洋 if(x1<0||y1<0||x1>=n||y1>=n||a[x1][y1]==0)continue; q.add(new int[] {x1,y1}); a[x1][y1]=0;//设置为海洋,不再遍历 } } } static FastReader in=new FastReader(); static PrintWriter out=new PrintWriter(System.out); static class FastReader{ static BufferedReader br; static StringTokenizer st; FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next() { String str=""; while(st==null||!st.hasMoreElements()) { try { str=br.readLine(); }catch(IOException e) { throw new RuntimeException(e); } st=new StringTokenizer(str); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } }
信息
- ID
- 33
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 3
- 标签
- 递交数
- 33
- 已通过
- 19
- 上传者