码迷,mamicode.com
首页 > 其他好文 > 详细

最少步数

时间:2015-04-15 14:57:48      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

最少步数

时间限制: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
来源
[苗栋栋]原创
上传者

苗栋栋

自己搜索不太好,参考代码网址:54楼

http://acm.nyist.net/JudgeOnline/talking.php?pid=58

#include<iostream>
#include<queue>
#include<string.h>
using namespace std;
int num[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 visit[9][9];
struct point
{
	int x;
	int y;
	int step;
};
void bfs(int startx,int starty,int endx,int endy)
{
	queue<point>q;
   	point now,next;
	int x[4]={0,1,0,-1};
        int y[4]={1,0,-1,0};
	int k,exit=0;
        now.step=0;
	now.x=startx;
	now.y=starty;
    q.push(now);
    while(!q.empty())
	{
		next=q.front();
		q.pop();
        if(next.x==endx &&next.y==endy)
		{
           exit=1;
		   break;
		}
		for(k=0;k<4;k++)
		{
			now.x=next.x+x[k];
			now.y=next.y+y[k];
			if(!visit[now.x][now.y] &&now.x>=0 &&now.x<9 &&now.y>=0 &&now.y<9 &&num[now.x][now.y]==0)
			{
                visit[now.x][now.y]=1;
				now.step=next.step+1;
				q.push(now);
			}
		}
	}
		if(exit)
			cout<<next.step<<endl;
		else
			cout<<-1<<endl;
}
int main()
{
	int a,b,c,d,T;
	cin>>T;
	while(T--)
	{
       cin>>a>>b>>c>>d;
	   memset(visit,0,sizeof(visit));
	   bfs(a,b,c,d);	  
	} 

	return 0;
}        

最少步数

标签:

原文地址:http://blog.csdn.net/zuguodexiaoguoabc/article/details/45058103

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!