【bfs】【图论】营救

在这里插入图片描述


思路:

直接bfs
dfs会TLE


C o d e Code Code:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
 
int fx[4][2] = {
    
    {
    
    0, 1}, {
    
    0, -1}, {
    
    1, 0}, {
    
    -1, 0}}; 
int g[1010][3],n,m,a[1010][1010],f[1010][1010];
int x1,y1,x2,y2;
char x;
void bfs()//bfs搜最短路
{
    
    
    int head = 0,tail = 1;
    while (head < tail)
    {
    
    
        head++;
        for (int i = 0;i <= 3;i++)
        {
    
    
            int x = g[head][0] + fx[i][0];
            int y = g[head][1] + fx[i][1];
            if (x >= 1 && x <= n && y >= 1 && y <= n && f[x][y] == 0)
            {
    
    
                tail++;
                g[tail][0] = x;
                g[tail][1] = y;
                a[x][y] = g[tail][2] = g[head][2] + 1; 
                f[x][y] = 1;
            }
            if (x == x2 && y == y2)
            {
    
    
            	printf("%d", a[x][y]);
            	return;
            }
        }
    }
}
int main()
{
    
    
	freopen("save.in","r",stdin);
	freopen("save.out","w",stdout);
    scanf("%d",&n);
    memset(f, 1,sizeof(f));
    for (int i = 1; i <= n; i++)
    	for (int j = 1; j <= n; j++)
    	{
    
    
    		cin>>x;
    		f[i][j] = (int)x - '0';//转换读入
    	}
    scanf("%d%d%d%d",&x1, &y1, &x2, &y2);
    g[1][0] = x1;
    g[1][1] = y1;
    bfs();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hunkwu/article/details/108154538