广度优先搜索(不写出路径,只写出步数)

我之前学习广度优先搜索有些感触,现在书写代码(这是一道最短路径求步数题)如果要写出路径,不可以用此方法,如果实验只进行一次,可将a[50][50]和book[50][50]合并处理
习惯把验证过程不删方便以后观看

#include <stdio.h>
//广度优先搜索
struct note {
	int x;
	int y;

};

int main() {

	struct note que[2][100];
	int a[50][50] = {0};
	int book[50][50] = {0};
	int n, m, tail, i, k, sx, sy, tx, ty, p, q, f, h, ste,e,w;
	f = 0;
	scanf("%d %d", &n, &m);
	for (i = 0; i < n; i++) {
		for (k = 0; k < m; k++) {

			scanf("%d", &a[i][k]);
		}
	}
	scanf("%d %d %d %d", &sx, &sy, &p, &q);
	int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
	ste = 0;
	tail = 0;
	que[0][tail].x = sx;
	que[0][tail].y = sy;
	book[sx-1][sy-1] = 1;
	h=1;
	while (1) {
		ste++;
		for (k = 0; k < h; k++) {
			for (i = 0; i < 4; i++) {
				tx = que[(ste - 1) % 2][k].x + d[i][0];
				ty = que[(ste - 1) % 2][k].y + d[i][1];
				if (sy < 1 || sx < 1 || sx > n || sy > m) {
					continue;
				}
				if (a[tx - 1][ty - 1] == 0 && book[tx - 1][ty - 1] == 0) {
					book[tx - 1][ty - 1] = ste;

					que[ste % 2][tail].x = tx;
					que[ste % 2][tail].y = ty;
					tail++;
					//printf("%d ", ste);
				}
				if (tx == p && ty == q) {
					printf("%d", ste);
					f = 1;
					break;
				}
			}
			if (f == 1) {
//				printf("来了");
				break;
			}
		}
/*	
		printf("\n");
		for(w=0;w<n;w++){
			for(e=0;e<m;e++){
				printf("%d ",book[w][e]);
			}
			printf("\n");
		}
		printf("%d\n",tail);
		
		h = tail;
		tail=0;
*/
		if (f == 1) {
//			printf("来啦");
			break;
		}

	}
	getchar();
	getchar();
	return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值