• P1443 马的遍历


    1. #include <iostream>
    2. #include <queue>
    3. using namespace std;
    4. #define M 400
    5. int arr[M + 5][M + 5];
    6. typedef struct Node {
    7. int x, y;
    8. } Node;
    9. //将马能走的8个方向封装成一个二维数组
    10. int dir[8][2] = {
    11. {2, 1}, {2, -1}, {-2, 1}, {-2, -1},
    12. {1, 2}, {-1, 2}, {1, -2}, {-1, -2}};
    13. void fun(int x, int y, int n, int m) {
    14. Node node;
    15. node.x = x, node.y = y;
    16. arr[x][y] = 0;
    17. queue<Node> q;
    18. q.push(node);
    19. //广搜
    20. while (!q.empty()) {
    21. int indx = q.front().x, indy = q.front().y;
    22. q.pop();
    23. for (int i = 0; i < 8; i++) {
    24. int x1 = indx + dir[i][0];
    25. int y1 = indy + dir[i][1];
    26. if (x1 < 1 || x1 > n) continue;
    27. if (y1 < 1 || y1 > m) continue;
    28. //遍历过了就直接跳过,因为是广搜,所以当前一定不如之前更优
    29. if (arr[x1][y1] != -1) continue;
    30. arr[x1][y1] = arr[indx][indy] + 1;
    31. Node n;
    32. n.x = x1, n.y = y1;
    33. q.push(n);
    34. }
    35. }
    36. return;
    37. }
    38. int main() {
    39. int n, m, x, y;
    40. cin >> n >> m >> x >> y;
    41. for (int i = 1; i <= n; i++) {
    42. for (int j = 1; j <= m; j++) {
    43. //先每行初始化-1
    44. arr[i][j] = -1;
    45. }
    46. }
    47. fun(x, y, n, m);
    48. for (int i = 1; i <= n; i++) {
    49. for (int j = 1; j <= m; j++) {
    50. cout << arr[i][j] << " ";
    51. }
    52. cout << endl;
    53. }
    54. return 0;
    55. }

  • 相关阅读:
    轻量级的开源代理服务器Tinyproxy安装与配置
    90.(cesium篇)cesium高度监听事件
    CP&FT测试介绍
    学习笔记-SQLi
    【无标题】
    Nginx学习总结(目录)
    算法:(贪心算法)-独木舟问题
    SPI:Java的高可扩展利器
    Redis面试题总结
    计算机网络概述
  • 原文地址:https://blog.csdn.net/Mz_yuner/article/details/133834830