走迷宫【Ybtoj】

D e s c r i p t i o n Description Description

现在有一个 N ∗ N N*N NN的地图,问从起点 ( s x , s y ) (sx, sy) (sx,sy)到(tx, ty)最少要走几步。

I n p u t Input Input

第一行一个正整数 N N N
接下来 N N N行,每行 N N N个字符,表示 N ∗ N N*N NN 0 / 1 0/1 0/1矩阵, 1 1 1表示不能通过, 0 0 0表示可以通过。
最后一行四个整数 s x , s y , t x , t y sx,sy,tx,ty sx,sy,tx,ty

O u t p u t Output Output

仅有一个数,表示答案。

S a m p l e Sample Sample I n p u t Input Input
5
01111
00111
10001
11101
11100
1 1 5 5
S a m p l e Sample Sample O u t p u t Output Output
8

H i n t Hint Hint

对于 100 % 100\% 100%的数据,有 1 ≤ N ≤ 1000 1 \leq N \leq 1000 1N1000

T r a i n Train Train o f of of T h o u g h t Thought Thought

数据不是非常大
就直接用广搜喽

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;

const int dx[5] = {
    
    0, 0, 0, 1, -1};
const int dy[5] = {
    
    0, 1, -1, 0, 0};

int A[1005][1005], Bol[1005][1005];
int dis[1005][1005];
int n, l, r;

bool Check(int x, int y)
{
    
    
	if(x > n || y > n || x < 1 || y < 1)return 0;
	if(A[x][y] || Bol[x][y])return 0;
	return 1;
}

void BFS(int a, int b)
{
    
    
	memset(Bol, 0, sizeof(Bol));
	memset(dis, 0, sizeof(dis));
	queue<int>hx, hy;
	hx.push(a), hy.push(b);
	Bol[a][b] = 1, dis[a][b] = 0;
	while(hx.size())
	{
    
    
		int xx = hx.front(); hx.pop();
		int yy = hy.front(); hy.pop();
		int x = xx + dx[1], y = yy + dy[1];
		for(int i = 1; i <= 4; i++)
			if(Check(xx + dx[i], yy + dy[i]))
			{
    
    
				x = xx + dx[i], y = yy + dy[i];
				dis[x][y] = dis[xx][yy] + 1;
				Bol[x][y] = 1;
				hx.push(x), hy.push(y);
				if(x == l && y == r)
				{
    
    
					printf("%d", dis[x][y]);
					exit(0);
				}
			}
	}
	return;
}

int main()
{
    
    
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i)
		for(int j = 1; j <= n; ++j)
		{
    
    
			char c;
			cin >> c;
			A[i][j] = c - '0';
		}	
	int x, y;
	scanf("%d%d%d%d", &x, &y, &l, &r);
	BFS(x, y);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SSL_wujiajie/article/details/112888304