有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的(上下左右四个方向)黑色瓷砖移动。
请写一个程序,计算你总共可以到达多少块黑色的瓷砖。java
输入包含多组数据。
每组数据第一行是两个整数 m 和 n(1≤m, n≤20)。紧接着 m 行,每行包括 n 个字符。每一个字符表示一块瓷砖的颜色,规则以下:
1. “.”:黑色的瓷砖;
2. “#”:白色的瓷砖;
3. “@”:黑色的瓷砖,而且你站在这块瓷砖上。该字符在每一个数据集合中惟一出现一次。算法
对应每组数据,输出总共可以到达多少块黑色的瓷砖。spa
9 6 ....#. .....# ...... ...... ...... ...... ...... #@...# .#..#.
45
能够将红色地板看做是障碍,从@地板出发,尝试不一样的走法,直到找出步的黑地板数最多的解决方案。由于走过的地板能够重复走,因此只要从起始点开始作广度优先遍历,记录能够访问的黑地板数就能够实现。code
import java.util.ArrayDeque; import java.util.Queue; import java.util.Scanner; /** * 改进方案 * Declaration: All Rights Reserved !!! */ public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt")); while (scanner.hasNext()) { int row = scanner.nextInt(); int col = scanner.nextInt(); int[][] floor = new int[row][col]; for (int i = 0; i < row; i++) { floor[i] = new int[col]; String line = scanner.next(); for (int j = 0; j < col; j++) { floor[i][j] = line.charAt(j); } } System.out.println(maxStep(floor)); } scanner.close(); } /** * 求能够走的地板的最大步数 * * @param floor 地板 * @return 步数 */ private static int maxStep(int[][] floor) { int x = 0; int y = 0; int row = floor.length; int col = floor[0].length; // 找起始位置 for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (floor[i][j] == '@') { x = i; y = j; } } } // 输出地板信息 // for (int[] line : floor) { // for (int e : line) { // System.out.print((char) e); // } // System.out.println(); // } return findPath(floor, x, y); } /** * 求能够走的黑地板的最大步数 * * @param floor 地板 * @param x 起始坐标 * @param y 起始坐标 */ private static int findPath(int[][] floor, int x, int y) { int row = floor.length; int col = floor[0].length; if (x < 0 || x >= row || y < 0 || y >= col || floor[x][y] == '#') { return 0; } // 记录待访问的位置,两个一组 Queue<Integer> queue = new ArrayDeque<>(row * col * 2); // 能够移动的四个方向,两个一组 int[] d = {1, 0, 0, 1, -1, 0, 0, -1}; queue.add(x); queue.add(y); // 最多能够走的黑地板数目 int result = 1; while (!queue.isEmpty()) { x = queue.remove(); y = queue.remove(); for (int i = 0; i < d.length; i += 2) { int t = x + d[i]; int v = y + d[i + 1]; if (t >= 0 && t < row && v >= 0 && v < col && floor[t][v] == '.') { // 标记已经访问过 floor[t][v] = '#'; // 计数器增长 result++; // 访问的位置添加到队列中 queue.add(t); queue.add(v); } } } return result; } }