NYOJ58

这篇博客主要探讨了如何用最短步数解决NYOJ58问题,作者提供了参考链接,包括一个关于BFS(广度优先搜索)详细做法的博客解析。


最少步数

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 4
描述

这有一个迷宫,有0~8行和0~8列:

 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

0表示道路,1表示墙。

现在输入一个道路的坐标作为起点,再如输入一个道路的坐标作为终点,问最少走几步才能从起点到达终点?

(注:一步是指从一坐标点走到其上下左右相邻坐标点,如:从(3,1)到(4,1)。)

输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
随后n行,每行有四个整数a,b,c,d(0<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。
输出
输出最少走几步。
样例输入
2
3 1  5 7
3 1  6 7
样例输出
12
11
#include<stdio.h>    
int a[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 t,x1,x2,y1,y2,m;    
int dfs(int x,int y,int s)    
{    
    if(x==x2&&y==y2)
	{
	if(m>s)
	m=s;//更新m为这个更小的值。 
	}    
    else    
        {    
        if(!a[x+1][y])  
		{a[x+1][y]=1;//上层标记,防止重复
		dfs(x+1,y,s+1);//对此层级以下情况递归遍历
		a[x+1][y]=0;//回溯为原值0
		}    
        if(!a[x-1][y])  {a[x-1][y]=1;dfs(x-1,y,s+1);a[x-1][y]=0;}    
        if(!a[x][y+1])  {a[x][y+1]=1;dfs(x,y+1,s+1);a[x][y+1]=0;}    
        if(!a[x][y-1])  {a[x][y-1]=1;dfs(x,y-1,s+1);a[x][y-1]=0;}    
    }    
}    
int main()    
{    
    int s;    
    scanf("%d",&t);    
    while(t--)    
    {    
        m=81;s=0;//m=81为最多步数,s为过程中的步数s=0从0步开始   
        scanf("%d %d %d %d",&x1,&y1,&x2,&y2);    
        dfs(x1,y1,s);    
        printf("%d\n",m);    
    }    
return 0;    
}    

参考博客:http://blog.csdn.net/better_space/article/details/52053940

http://www.cnblogs.com/orange1438/p/4063675.html

BFS做法详见博客:http://blog.csdn.net/qq_29600137/article/details/52049240

 
# include<stdio.h>
# include<string.h>
# include<queue>
using namespace std;
int c1,c2,k1,k2,v[4][2]={1,0,0,1,-1,0,0,-1};	
int c[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,
};
struct stu{
	int a;
	int b;
	int step;
}q1,q2;
void w(int x,int y)
{
int a[9][9]={0};	
	queue<stu>p;
	q1.a=x;
	q1.b=y;
	q1.step=0;
	p.push(q1);
	while(!p.empty())
	{
	q1=p.front();
	p.pop();
	a[q1.a][q1.b]=1;	
	if(q1.a==k1&&q1.b==k2)
	{
		printf("%d\n",q1.step);break;
	}	
	for(int i=0;i<4;i++)
	{
	q2.a=q1.a+v[i][0];	
	q2.b=q1.b+v[i][1];
	q2.step=q1.step+1;	
	if(q2.a>=0&&q2.a<9&&q2.b>=0&&q2.b<9&&c[q2.a][q2.b]==0&&a[q2.a][q2.b]==0)
	{
		p.push(q2);
		
	}
		
	}
	}
	
}
int main(){
int t;	
	scanf("%d",&t);
	while(t--)
	{	
		scanf("%d%d%d%d",&c1,&c2,&k1,&k2);		
		w(c1,c2);		
	}
	return 0;
}        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值