求空地的个数



package work;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AvacantRoom {
  static char  map[][];
     static int  data[][];
     static int N,M;
     static int resum;
     static int []Dx={-1,-1,0,1,1,1,0,-1};
     static int []Dy={0,1,1,1,0,-1,-1,-1};
     static class Node{
      int x;
      int y;
     }
     static Node queue[];
 public static void main(String[] args) throws FileNotFoundException {
 /* Scanner sc=new Scanner(System.in);*/
  Scanner sc=new Scanner(new File("src/vacantRoom"));
  while(true){
   N=sc.nextInt();
   M=sc.nextInt();
   map=new char[N][M];
   data=new int[N][M];
   
   if(N==0||M==0){break;}
   resum=0;
   sc.nextLine();
   for (int i = 0; i < N; i++) {
    char[] line=sc.nextLine().toCharArray();
    for (int j = 0; j < line.length; j++) {
     map[i][j]=line[j];
     if(map[i][j]=='+'){data[i][j]=1;}
     else{data[i][j]=0;}
    }
   }
   for (int i = 0; i < N; i++) {
    for (int j = 0; j < M; j++) {
     if(data[i][j]==0){
      bfs(i,j);
     }
    }
   }
  System.out.println(resum);
   /*for (int i = 0; i < N; i++) {
    for (int j = 0; j <M; j++) {
     System.out.print(data[i][j]);
    }
    System.out.println();
   }*/
  }
 }
 private static void bfs(int x, int y) {
  queue=new Node[N*M];
  resum+=1;
  int head=0;
  int tail=0;
  data[x][y]=2;
  Node n1=new Node();
  n1.x=x;
  n1.y=y;
  queue[tail++]=n1;
  while(head<tail){
   for (int i = 0; i < 8; i++) {
    int dx=queue[head].x+Dx[i];
    int dy=queue[head].y+Dy[i];
    if(dx>=0&&dx<N&&dy>=0&&dy<M&&data[dx][dy]==0){
     data[dx][dy]=2;
     Node n2=new Node();
     n2.x=dx;
     n2.y=dy;
     queue[tail++]=n2;
    }
   }
   head++;
  }
  
 }

}

、、input

6 4
++++
+  +
+  +
++++
+  +
++++
6 4
++++
+  +
++ +
+ ++
+  +
++++
0 0

、、output

2
1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值