201312-5 I'm stuck!
阿新 • • 發佈:2018-12-06
1、深搜找到起點可以到達的所有點,如果其中不包括終點,輸入I'm stuck
2、深搜每一個起點可到達的點,如果其不可以到達終點,計數器加一
奉上java滿分程式碼
import java.util.Scanner; public class Main { private static char[][] map; private static int r, c; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] firstLine = scanner.nextLine().split(" "); r = Integer.parseInt(firstLine[0]); c = Integer.parseInt(firstLine[1]); map = new char[r][c]; int startI = 0, startJ = 0, endI = 0, endJ = 0; for(int i = 0; i < r; i++){ String line = scanner.nextLine(); for(int j = 0; j < c; j++){ char ch = line.charAt(j); map[i][j] = ch; if(ch == 'S'){ startI = i; startJ = j; } else if(ch == 'T'){ endI = i; endJ = j; } } } scanner.close(); boolean[][] canStartArrivePoints = new boolean[r][c]; getReachablePoints(startI, startJ, canStartArrivePoints); if(canStartArrivePoints[endI][endJ]){ int count = 0; for(int i = 0; i < r; i++){ for(int j = 0; j < c; j++){ if(canStartArrivePoints[i][j]){ boolean[][] points = new boolean[r][c]; getReachablePoints(i, j , points); if(!points[endI][endJ]) count++; } } } System.out.println(count); } else{ System.out.println("I'm stuck!"); } } private static void getReachablePoints(int i , int j, boolean[][] points){ if(i < 0 || j < 0 || i > r - 1 || j > c - 1) return; if(points[i][j]) return; char ch = map[i][j]; if(ch == '#') return; points[i][j] = true; switch (ch){ case 'S': case 'T': case '+': getReachablePoints(i - 1, j, points); getReachablePoints(i + 1, j, points); getReachablePoints(i, j - 1, points); getReachablePoints(i, j + 1, points); break; case '-': getReachablePoints(i, j - 1, points); getReachablePoints(i, j + 1, points); break; case '|': getReachablePoints(i - 1, j, points); getReachablePoints(i + 1, j, points); break; case '.': getReachablePoints(i + 1, j, points); break; } } }