广度搜索 3,4,8,9没有过,求助急急急!!!
查看原帖
广度搜索 3,4,8,9没有过,求助急急急!!!
866969
telankesi楼主2022/12/28 16:42
#include <stdio.h>
struct node {
    int x, y;//坐标
    int s;//步数
};
int a[402][402], book[402][402];//a用于记录步数,book标记走过
int main(){
    int n, m, x, y;
    scanf("%d %d %d %d", &n, &m, &x, &y);//x,y为马的坐标
    struct node que[2501];//创建队列
    int head, tail;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            a[i][j] = -1;
        }
 }
    a[x][y] = 0;
    int next[8][2] = { {1,2} ,{2,1}, {1,-2},{2,-1 } ,{-1,2} ,{-1,-2}, {-2,1}, {-2,-1} };
    
    int  tx, ty;
    head = 1; tail = 1;
    que[tail].x = x;
    que[tail].y = y;
    que[tail].s = 0;
    tail++;
    book[x][y] = 1;
    while (head < tail) {
        for (int i = 0; i < 8; i++) {
            tx = que[head].x + next[i][0];
            ty = que[head].y + next[i][1];

            if (tx<1 || tx>n || ty<1 || ty>m)continue;
            if (book[tx][ty] == 0 &&( tx != x || ty != y)) {
                book[tx][ty] = 1;
                que[tail].x = tx;
                que[tail].y = ty;
                que[tail].s = que[head].s + 1;
                tail++;
                a[tx][ty] = que[head].s + 1;
            }
        }
        head++;
      
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            printf("%d ", a[i][j]);
        }printf("\n");
    }
	return 0;

}
2022/12/28 16:42
加载中...