华为9.7号笔试第二题,速战速决,帮忙看看能不能ac~
import java.util.*; import java.util.stream.Collectors; public class Main { private static boolean[][] boolArr; private static int points = Integer.MAX_VALUE; private static int m; private static int n; private static boolean f = false; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] s = scanner.nextLine().split(" "); m = Integer.parseInt(s[0]); n = Integer.parseInt(s[1]); boolArr = new boolean[m][n]; StringBuffer[] arr = new StringBuffer[m]; for (int i = 0; i < m; i++) { StringBuffer tmp = new StringBuffer(scanner.nextLine()); arr[i] = tmp; } int a1 = 0, a2 = 0, a3 = 0, a4 = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { boolArr[i][j] = false; char c = arr[i].charAt(j); if (c == 'S') { a1 = i; a2 = j; } else if (c == 'E') { a3 = i; a4 = j; } else if (c == 'X') { boolArr[i][j] = true; } } } getPoint(arr, a1, a2, a3, a4, 0, 0, 0, 0); if (points == Integer.MAX_VALUE) { System.out.println(-1); } else { System.out.println(points); } } private static void getPoint(StringBuffer[] arr, int a1, int a2, int a3, int a4, int a5, int a6, int nowPoint, int step) { if (a1 >= m || a2 >= n || a1 < 0 || a2 < 0 || boolArr[a1][a2] || (f && points <= nowPoint)) return; if (a1 == a3 && a2 == a4) { if (nowPoint < points) { points = nowPoint; f = true; } return; } boolArr[a1][a2] = true; if (step >= 1) { if (a1 == a5) { //横向走 getPoint(arr, a1 + 1, a2, a3, a4, a1, a2, nowPoint + 2, step + 1); getPoint(arr, a1 - 1, a2, a3, a4, a1, a2, nowPoint + 2, step + 1); getPoint(arr, a1, a2 + 1, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1, a2 - 1, a3, a4, a1, a2, nowPoint + 1, step + 1); } else if (a2 == a6) { //纵向走 getPoint(arr, a1 + 1, a2, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1 - 1, a2, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1, a2 + 1, a3, a4, a1, a2, nowPoint + 2, step + 1); getPoint(arr, a1, a2 - 1, a3, a4, a1, a2, nowPoint + 2, step + 1); } } else { //第一次,只能费一分钟 getPoint(arr, a1 + 1, a2, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1 - 1, a2, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1, a2 + 1, a3, a4, a1, a2, nowPoint + 1, step + 1); getPoint(arr, a1, a2 - 1, a3, a4, a1, a2, nowPoint + 1, step + 1); } boolArr[a1][a2] = false; } }
#华为笔试##笔试##华为笔试好难啊,自闭了#