NYOJ 58 最少步数问题

本文介绍了一种求解迷宫最短路径的算法实现,通过深度优先搜索(DFS)遍历迷宫地图,寻找从起点到终点的最短步数。文章提供了两种不同的C语言实现方式,并详细展示了如何使用递归进行路径探索。

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

//修改版

#include<stdio.h>
#include<string.h>
int arr[9][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,
};
int book[9][9];
int Next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int starx, stary, endx, endy;
int min_step = 999999;
void DFS(int x, int y,int step)
{
	if(x == endx && y == endy)
	{
		if(step < min_step)
		min_step = step;
		return ;
	}
	int i,tempx,tempy;
	for(i = 0;i<4;i++)
	{
		tempx = x + Next[i][0];
		tempy = y + Next[i][1];
		if(tempx < 1 || tempx > 8 || tempy < 1 || tempy > 8)
		continue;
		if(arr[tempx][tempy] == 0 && book[tempx][tempy] == 0)
		{
			book[tempx][tempy] = 1;
			DFS(tempx,tempy,step + 1);
			book[tempx][tempy] = 0;
		}
	}
	return ;
	
}
int main()
{
	int N;
	scanf("%d",&N);
	while(N--)
	{
		min_step = 999999;
		scanf("%d %d %d %d",&starx,&stary,&endx,&endy);
		memset(book, 0, sizeof(book));
		book[starx][stary] = 1;
		DFS(starx,stary,0);
		printf("%d\n",min_step);
	}
	return 0;
 } 




//两个月后重新看这个感觉简单了很多,优化后:


#include<cstdio>
#define min(x,y) x>y?y:x
int arr[9][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,  
};
int a, b, ea, eb, min_step;
void dfs(int x, int y, int step)
{
	if(arr[x][y])
	return ;
	if(x == ea && y == eb)
	{
		min_step = min(step,min_step);
		return ;
	}
	arr[x][y] = 1;
	dfs(x+1,y,step+1);
	dfs(x,y+1,step+1);
	dfs(x-1,y,step+1);
	dfs(x,y-1,step+1);
	arr[x][y] = 0;
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		min_step = 0xfffff;
		scanf("%d%d%d%d",&a,&b,&ea,&eb);
		dfs(a, b, 0);
		printf("%d\n",min_step);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值