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

NYOJ 58 最少步数 【BFS】

时间:2014-08-09 11:38:27      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:bfs

题意:不解释。

策略:如题;

这道题可以用深搜也可以用广搜,我以前写的是用的深搜,最近在学广搜,就拿这道题来练练手。

代码:

#include<stdio.h>
#include<string.h>
#include<queue>
using std::queue;
bool vis[20][20];
const int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};//方向
int map[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 Node{
	int pos[2];//pos[0] = x, pos[1] = y
	int step;
};
Node st, en;
bool match(Node a, Node b)  //判断是不是到达终点
{
	return (a.pos[0] == b.pos[0]&&a.pos[1] == b.pos[1]);
}
int bfs()
{
	queue<Node> q;
	int i, j;
	memset(vis, 0, sizeof(vis)); 
	q.push(st);
	vis[st.pos[0]][st.pos[1]] = 1;
	int ans = 0x3f3f3f3f;  //初始化
	while(!q.empty()){
		Node u = q.front();
		if(match(u, en)){    //wa了一次是因为没有判断终点是不是起点
			ans = u.step;
			break;
		}
		for(i = 0; i < 4; i ++){
			Node v;
			v.pos[0] = u.pos[0]+dir[i][0];
			v.pos[1] = u.pos[1]+dir[i][1];
			v.step = u.step+1;
			if(match(v, en)){
				if(v.step < ans)
				ans = v.step;
			}
			else if(!vis[v.pos[0]][v.pos[1]]&&!map[v.pos[0]][v.pos[1]]){
				q.push(v);
				vis[v.pos[0]][v.pos[1]] = 1;
			}
		}
		q.pop();
	}
	return ans;
}
int main()
{
	int t;
	scanf("%d", &t);
	while(t --){
		scanf("%d%d%d%d", &st.pos[0], &st.pos[1], &en.pos[0], &en.pos[1]);
		st.step = 0;
		printf("%d\n", bfs());
	}
	return 0;
}


题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=58


NYOJ 58 最少步数 【BFS】,布布扣,bubuko.com

NYOJ 58 最少步数 【BFS】

标签:bfs

原文地址:http://blog.csdn.net/shengweisong/article/details/38454421

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