有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。
你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共能够到达多少块黑色的瓷砖。
输入格式:
输入包括多个数据集合。
每个数据集合的第一行是两个整数 W 和 H ,分别表示 x 方向和 y 方向瓷砖的数量。
在接下来的 H 行中,每行包括 W 个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖; 2)‘#’:红色的瓷砖; 3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出格式:
对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。
数据范围:
1≤W,H≤20
输入样例:
输出样例:
45
解题思路:能走的点标记一下就行,输入输出就用while循环,碰到0 0 就退出。最后数一下标记点就行。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true){
int n = sc.nextInt();
int m = sc.nextInt();
if(n == 0) return;
String s = sc.nextLine();
char a[][] = new char[m][n];
for(int i = 0; i < m; i ++) {
s = sc.nextLine();
a[i] = s.toCharArray();
}
eds : for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
if(a[i][j] == '@') {
bfs(a, i, j);
break eds;
}
int sum = 0;
for(int i = 0; i < m; i ++)
for(int j = 0; j < n; j ++)
if(a[i][j] =='1') sum ++;
System.out.println(sum);
}
}
public static void bfs(char a[][], int i, int j) {
a[i][j] = '1';
int fx[] = {-1, 1, 0, 0};
int fy[] = {0, 0, -1, 1};
Queue<Integer> qux = new LinkedList<>();
Queue<Integer> quy = new LinkedList<>();
qux.offer(i);
quy.offer(j);
int fxx = 0, fyy = 0;
while(!qux.isEmpty()) {
for(int z = 0; z < 4; z ++) {
fxx = (int)qux.peek() + fx[z];
fyy = (int)quy.peek() + fy[z];
if(fxx >= 0 && fxx < a.length && fyy >= 0 && fyy < a[0].length && a[fxx][fyy] == '.') {
a[fxx][fyy] = '1';
qux.offer(fxx);
quy.offer(fyy);
}
}
qux.poll();
quy.poll();
}
}
}