NYOJ58最小步数(神搜)

本文介绍了一个使用递归回溯方法寻找二维迷宫中从起点到终点最短路径的C语言程序。通过设定不同的方向移动并记录每一步的状态,算法能够有效地找到最短路径。该程序适用于解决简单的迷宫问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include<stdio.h>
int min_step = 1000000;
int c,d;
int map[][9]={{1,1,1,1,1,1,1,1,1},
	{1,0,0,1,0,0,1,0,1},
	{1,0,0,1,1,0,0,0,1},
	{1,0,1,0,1,1,0,1,1},
	{1,0,0,0,0,1,0,0,1},
	{1,1,0,1,0,1,0,0,1},
	{1,1,0,1,0,1,0,0,1},
	{1,1,0,1,0,0,0,0,1},
	{1,1,1,1,1,1,1,1,1},
};
void count(int step, int x, int y)//step:当前步数,x:横坐标,y: 总坐标
{
	int i;
	int m, n;
//	printf("%d %d\n",x,y);
	if( min_step < step)//他在某一步已经超过了最小步数就不继续往下走了
		return;
	if(x == c && y == d )
		min_step = step;//到达终点的时候,重新判断mix_step的值
	else
	{
		for(i = 1; i <= 4; i ++)
		{
			m = x, n = y;//这里很巧妙,不能改变X,Y的值但是又要使调用的结果 是方向改变后的坐标值
			if( i == 1)
				n --;//down
			else if ( i == 2)
				m ++;//right
			else if(i == 3)
				n ++;//up
			else
				m --;//left
			if( map[m][n] == 0)
			{
				map[m][n] = 1;
				count(step + 1, m, n);
				map[m][n] = 0;
			}
		}
	}
}

int main ()
{
	int a,b;
	int n;
	scanf("%d",&n);
	while(n--)
	{
		scanf("%d%d%d%d",&a,&b,&c,&d);
		count(0,a,b);
		printf("%d\n",min_step);
		min_step = 10000;//注意这里每一次循环结束都要重置
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值