输入输出

  1. // ★ 别忘记引入这个包
  2. import java.util.*;
  3. // 字符串输入
  4. Scanner sc = new Scanner(System.in);
  5. String s = sc.nextLine();

模板

  1. import java.util.*;
  2. public class Main {
  3. public static void main(String[] args) {
  4. Scanner in = new Scanner(System.in);
  5. while (in.hasNext()) {
  6. }
  7. }
  8. }

ASCII 字母/数字转换

HJ43迷宫问题

  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Stack;
  6. public class Main {
  7. public static int[][] directions = {
  8. {0, 1},
  9. {1, 0},
  10. {-1, 0},
  11. {0, -1}
  12. };
  13. private static Stack<int[]> path;
  14. private static ArrayList<int[]> minPath;
  15. private static int[][] matrix;
  16. private static boolean[][] visited;
  17. public static void main(String[] args) throws Exception {
  18. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  19. String str1 = null;
  20. while ((str1 = br.readLine()) != null) {
  21. String[] arr = str1.split(" ");
  22. int rows = Integer.parseInt(arr[0]);
  23. int cols = Integer.parseInt(arr[1]);
  24. path = new Stack<>();
  25. minPath = null;
  26. matrix = new int[rows][cols];
  27. visited = new boolean[rows][cols];
  28. for (int i = 0; i < rows; i++) {
  29. String[] str2 = br.readLine().split(" ");
  30. for (int j = 0; j < cols; j++) {
  31. matrix[i][j] = Integer.parseInt(str2[j]);
  32. }
  33. }
  34. dfs(0, 0);
  35. StringBuilder sb = new StringBuilder();
  36. for (int[] res : minPath) {
  37. sb.append('(').append(res[0]).append(',').append(res[1]).append(")\n");
  38. }
  39. System.out.print(sb.toString());
  40. }
  41. }
  42. private static void dfs(int i, int j) {
  43. if (i > matrix.length - 1 || i < 0 || j > matrix[0].length - 1 || j < 0 ||
  44. visited[i][j] || matrix[i][j] == 1 ||
  45. (minPath != null && path.size() >= minPath.size())) {
  46. return;
  47. }
  48. if (i == matrix.length - 1 && j == matrix[0].length - 1) {
  49. path.add(new int[]{i, j});
  50. minPath = new ArrayList<>(path);
  51. path.pop();
  52. return;
  53. }
  54. path.add(new int[]{i, j});
  55. visited[i][j] = true;
  56. for (int[] direction : directions) {
  57. dfs(i + direction[0], j + direction[1]);
  58. }
  59. visited[i][j] = false;
  60. path.pop();
  61. }
  62. }