• 洛谷 P1443 马的遍历 Java


    1. import java.util.*;
    2. import java.io.*;
    3. public class Main{
    4. static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    5. static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    6. static boolean[][] judge;
    7. static int[][] distance;
    8. static int[] X = new int[] {-1,-2,-2,-1,1,2,2,1};
    9. static int[] Y = new int[] {2,1,-1,-2,2,1,-1,-2};
    10. static int n,m,x,y;
    11. public static void main(String[] args) throws IOException {
    12. String[] S = br.readLine().split(" ");
    13. n = Integer.parseInt(S[0]);
    14. m = Integer.parseInt(S[1]);
    15. x = Integer.parseInt(S[2]);
    16. y = Integer.parseInt(S[3]);
    17. distance = new int[n+1][m+1];
    18. judge = new boolean[n+1][m+1];
    19. for(int i = 1 ; i <= n ; i++) {
    20. for(int j = 1 ; j <= m ; j++) {
    21. distance[i][j] = -1;
    22. }
    23. }
    24. distance[x][y] = 0;
    25. BFS();
    26. for(int i = 1 ; i <= n ; i++) {
    27. for(int j = 1 ; j <= m ; j++) {
    28. System.out.printf("%-5d",distance[i][j]);
    29. }
    30. System.out.println();
    31. }
    32. out.flush();
    33. out.close();
    34. br.close();
    35. }
    36. private static void BFS() {
    37. Point begin = new Point();
    38. begin.x = x;
    39. begin.y = y;
    40. Deque deque = new LinkedList<>();
    41. deque.offer(begin);
    42. while(!deque.isEmpty()) {
    43. Point p = deque.poll();
    44. judge[p.x][p.y] = true;
    45. for(int i = 0 ; i < 8 ; i++) {
    46. int a = p.x + X[i];
    47. int b = p.y + Y[i];
    48. Point node;
    49. if(a >= 1 && a <= n && b >= 1 && b<= m && !judge[a][b]) {
    50. if(distance[a][b] == -1) {
    51. distance[a][b] = distance[p.x][p.y] + 1;
    52. }
    53. else {
    54. distance[a][b] = Math.min(distance[a][b],distance[p.x][p.y]+1);
    55. }
    56. node = new Point();
    57. node.x = a;
    58. node.y = b;
    59. judge[a][b] = true;
    60. deque.offer(node);
    61. }
    62. }
    63. }
    64. }
    65. }
    66. class Point{
    67. int x;
    68. int y;
    69. }

  • 相关阅读:
    【C++】内存管理——new与delete
    基于Springboot实现疫情网课管理系统项目【项目源码+论文说明】
    模拟实现vector
    软件定制开发具有以下特点|APP搭建|小程序
    运筹说 第76期 | 最短路问题
    LeetCode //C - 136. Single Number
    C++:指针:void*指针(跳跃力未定的指针)
    手撕前端面试题【javascript】
    CentOS7 离线部署 Python 项目
    cpp primer plus笔记06-函数
  • 原文地址:https://blog.csdn.net/Gengar021127/article/details/133848503