题目来源:《信息学奥赛一本通》
时间限制:1000ms 内存限制:64mbjava
有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。
你站在其中一块黑色的瓷砖上,只能向相邻(上下左右四个方向)的黑色瓷砖移动。
请写一个程序,计算你总共可以到达多少块黑色的瓷砖。shell
输入包括多个数据集合。
每一个数据集合的第一行是两个整数 \(W\) 和 \(H\),分别表示 \(x\) 方向和 \(y\) 方向瓷砖的数量。
在接下来的 \(H\) 行中,每行包括 \(W\) 个字符。每一个字符表示一块瓷砖的颜色,规则以下
1)‘.’:黑色的瓷砖;
2)‘#’:红色的瓷砖;
3)‘@’:黑色的瓷砖,而且你站在这块瓷砖上。该字符在每一个数据集合中惟一出现一次。
当在一行中读入的是两个零时,表示输入结束。ide
对每一个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。this
\(1 ≤ W,H ≤ 20\)code
6 9 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#. 0 0
45
先将初始坐标加入队列。
而后,遍历当前格子的上下左右四个格子,若是能找到'.',则将他的坐标加入队列。
而后依次作下去,每走到一个新的格子,计数+1
直到队列为空,也就完成了全部遍历。
计数的值就是题解。递归
在Java中,LinkedList类实现了Queue接口,所以咱们能够把LinkedList当成Queue来用。
其中,add()和remove()方法在失败的时候会抛出异常,而offer()和poll()不会,因此这里使用offer()和poll()。接口
import java.util.*; class pair { int x, y; public pair(int sx, int sy) { this.x = sx; this.y = sy; } } public class Main { public static int N = 30; public static int h, w; public static char[][] g = new char[N][N]; public static int[] dx = {-1, 0, 1, 0}; public static int[] dy = {0, 1, 0, -1}; static int bfs(int sx, int sy) { pair p = new pair(sx, sy); Queue<pair> q = new LinkedList<>(); q.offer(p); g[sx][sy] = '#'; int res = 0; while (!q.isEmpty()) { pair t = q.poll(); res++; for (int i = 0; i < 4; i++) { int x = t.x + dx[i]; int y = t.y + dy[i]; if (x < 0 || x >= h || y < 0 || y >= w || g[x][y] != '.') { continue; } g[x][y] = '#'; q.offer(new pair(x, y)); } } return res; } public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { String[] ts = input.nextLine().split(" "); w = Integer.parseInt(ts[0]); h = Integer.parseInt(ts[1]); if (w == 0 || h == 0) { break; } int x = 0, y = 0; for (int i = 0; i < h; i++) { String str = input.nextLine(); for (int j = 0; j < w; j++) { g[i][j] = str.charAt(j); if (g[i][j] == '@') { x = i; y = j; } } } System.out.println(bfs(x, y)); } input.close(); } }
深度优先搜索,因为有不少层递归,有可能爆栈。
虽然DFS代码更加简单,但仍是建议使用BFS解决此题。队列
遍历当前坐标的上下左右四个格子,若是是'.',则当即遍历找到的'.'的格子的上下左右,如此进行递归。
每层递归返回找到的'.'的数量。
最后获得的数量即为题解。内存
import java.util.*; public class Main { public static int N = 30; public static int h, w; public static char[][] g = new char[N][N]; public static int[] dx = {-1, 0, 1, 0}; public static int[] dy = {0, 1, 0, -1}; static int dfs(int sx, int sy) { int res = 1; g[sx][sy] = '#'; for (int i = 0; i < 4; i++) { int x = sx + dx[i]; int y = sy + dy[i]; if (x >= 0 && x < h && y >= 0 && y < w && g[x][y] == '.') { res += dfs(x, y); } } return res; } public static void main(String[] args) { Scanner input = new Scanner(System.in); while (true) { String[] ts = input.nextLine().split(" "); w = Integer.parseInt(ts[0]); h = Integer.parseInt(ts[1]); if (w == 0 || h == 0) { break; } int x = 0, y = 0; for (int i = 0; i < h; i++) { String str = input.nextLine(); for (int j = 0; j < w; j++) { g[i][j] = str.charAt(j); if (g[i][j] == '@') { x = i; y = j; } } } System.out.println(dfs(x, y)); } input.close(); } }