链接
题目描述
现在有一个 N*N 的地图,问从起点 (sx,sy) 到 (tx,ty) 最少要走几步。
样例输入
5
01111
00111
10001
11101
11100
1 1 5 5
样例输出
8
思路
直接广搜,如果有能到的点就加入队列,满足条件就立刻输出
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LYF using
#define AK namespace
#define IOI std;
LYF AK IOI//%%%
int sx, sy, tx, ty, n;
int dx[4] = {
0, 0, 1, -1};
int dy[4] = {
1, -1, 0, 0};
int a[1005][1005], d[1005][1005], vis[1005][1005];
bool check(int x, int y)
{
if(x > n || x < 1 || y > n || y < 1) return 0;
return 1;
}//判断是否越界
void BFS()
{
memset(d, 0, sizeof(d));
memset(vis, 0, sizeof(vis));
queue<pair<int, int> >Q;
Q.push(make_pair(sx, sy));
d[sx][sy] = 0;
vis[sx][sy] = 1;
while(Q.size())
{
pair<int, int>tot = Q.front();
Q.pop();
int x = tot.first, y = tot.second;
if(x == tx && y == ty)
{
printf("%d\n", d[x][y]);
return;
}
for(int i = 0; i < 4; ++i)
{
int nx = x + dx[i];
int ny = y + dy[i];//向四面搜索
if(!vis[nx][ny] && check(nx, ny) && a[nx][ny] == 0)
{
d[nx][ny] = d[x][y] + 1;
vis[nx][ny] = 1;
Q.push(make_pair(nx, ny));//加入队列
}
}
}
}
int main()
{
scanf("%d", &n);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
scanf("%1d", &a[i][j]);
scanf("%d%d%d%d", &sx, &sy, &tx, &ty);
BFS();
return 0;
}