ccf 201312-05 I'm stuck (java100分)
阿新 • • 發佈:2018-12-05
使用dfs,根據題目要求搜尋滿足要求的點即可。
耗時234ms
import java.util.Scanner; public class Main { private static int rows; private static int cols; private static char[][] map; private static int startI, startJ; private static int endI, endJ; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] firstLine = scanner.nextLine().split(" "); rows = Integer.parseInt(firstLine[0]); cols = Integer.parseInt(firstLine[1]); map = new char[rows][cols]; for (int i = 0; i < rows; i++) { String line = scanner.nextLine(); for (int j = 0; j < cols; j++) { char c = line.charAt(j); map[i][j] = c; if (c == 'S') { startI = i; startJ = j; } if (c == 'T') { endI = i; endJ = j; } } } scanner.close(); boolean[][] startVisited = new boolean[rows][cols]; getRoads(startI, startJ, startVisited); if(!startVisited[endI][endJ]){ System.out.println("I'm stuck!"); } else { int count = 0; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (startVisited[i][j]) { boolean[][] visited = new boolean[rows][cols]; getRoads(i, j, visited); if (!visited[endI][endJ]) count++; } } } System.out.println(count); } } private static void getRoads(int i, int j, boolean[][] visited) { if (i < 0 || i >= rows || j < 0 || j >= cols) return; if (visited[i][j]) return; char c = map[i][j]; if (c == '#') return; visited[i][j] = true; switch (c) { case '|': getRoads(i + 1, j, visited); getRoads(i - 1, j, visited); break; case '.': getRoads(i + 1, j, visited); break; case '+': case 'S': case 'T': getRoads(i + 1, j, visited); getRoads(i - 1, j, visited); getRoads(i, j - 1, visited); getRoads(i, j + 1, visited); break; case '-': getRoads(i, j - 1, visited); getRoads(i, j + 1, visited); break; } } }