NYOJ - 58:最少步数

最少步数

来源:NYOJ

标签:图论,宽度优先搜索

参考资料:

相似题目:

题目

这有一个迷宫,有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(1<=a,b,c,d<=8)分别表示起点的行、列,终点的行、列。

输出

输出最少走几步。

输入样例

2
3 1 5 7
3 1 6 7

输出样例

12
11

参考代码

#include
#include
#include
using namespace std;
int maze[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 vis[9][9];
int dx[4]={0,-1,0,1};
int dy[4]={-1,0,1,0};
int a,b,c,d;

void bfs(){
	queue<int> posx;
	queue<int> posy;
	posx.push(a);
	posy.push(b);
	int x=a,y=b;
	while(x!=c || y!=d){
		posx.pop();
		posy.pop();
		for(int i=0;i<4;i++){
			int nx=x+dx[i];
			int ny=y+dy[i];
			if(nx>=1 && nx<8 && ny>=1 && ny<8 && !maze[nx][ny] && !vis[nx][ny]){
				vis[nx][ny]=vis[x][y]+1;
				posx.push(nx);
				posy.push(ny);
			}
		}
		x=posx.front();
		y=posy.front();
	}
}

int main(){
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		memset(vis,0,sizeof(vis));
		scanf("%d%d%d%d",&a,&b,&c,&d);
		bfs();
		printf("%d\n",vis[c][d]);
	}
	return 0;
}

你可能感兴趣的:(【记录】算法题解)