欢迎来到 嗅灵易学

零基础也能上手的脚本技术课,一对一答疑带你入门

答复

答复

BFS

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int dir[][2] = {{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
int q[51*51][3];
int step[51][51];
void output(int k)
{
  if (q[k][2] == -1) {printf("(1,1)"); return;}
  output(q[k][2]);
  printf("->(%d,%d)",q[k][0],q[k][1]);  
}
int main()
{
  int head, tail, m, n, tx, ty, d;
  memset(step, -1, sizeof(step));
  scanf("%d%d",&n,&m);
  q[0][0] = q[0][1] = 1; q[0][2] = -1;
  step[1][1] = 0; head = 0; tail = 1;
  while (head < tail) {
    if (q[head][0] == n && q[head][1] == m) break;
    for (d = 0 ; d < 8 ; d++) {
      tx = q[head][0] + dir[d][0];
      ty = q[head][1] + dir[d][1];
      if (tx >= 1 && tx <= 50 && ty >= 1 && ty <= 50 && step[tx][ty] == -1) {
        step[tx][ty] = step[q[head][0]][q[head][1]] + 1;
        q[tail][0] = tx;
        q[tail][1] = ty;
        q[tail++][2] = head;
      }
    }
    ++head;
  }
  if (step[m][n] == -1) printf("error!\n");
  else {
    printf("STEP:%d\n",step[m][n]);
    output(head);
    printf("\n");
  }
  system("pause");
  return 0;
}

注意:上传附件及图片大小不得大于30M。

⚠️ 版权声明:
本博客所有内容(含教程、源码、工具)仅供个人技术学习与研究交流使用,严禁商用、倒卖、二次分发及非法用途
未经作者书面授权,任何组织或个人不得转载、复制或用于其他平台,违者将追究相关责任。

0 0 0 举报
复制成功