求助,一直输出-1
查看原帖
求助,一直输出-1
735797
XingnoYi楼主2024/3/9 22:30
#include <iostream>
#include <queue>
#include <stack>
#define big long long
using namespace std;
struct Node{
	big x,y;
};
big T,n,m,to[2][4]={1,0,0,1,-1,0,0,-1};
char map[2004][2004],path[5]={' ','D','R','U','L'};
big dis[2004][2004],vis[2004][2004],ways[2004][2004];
bool in_map(big x,big y)
{
	return (1 <= x && x <= n && y >= 1 && y <= m);
}
void bfs(big sx,big sy)
{
	queue <Node> q;
	q.push(Node({sx,sy}));
	dis[sx][sy] = 0;
	vis[sx][sy] = 1;
	while(!q.empty())
	{
		Node pos=q.front();
		q.pop();
		if(pos.x == n && pos.y == m)
		{
			printf("%lld\n",dis[n][m]);
            stack <big> st;
            big ex = n,ey = m;
            while(ex != 1 && ey != 1)
            {
                st.push(ways[ex][ey]);
                big back = (ways[ex][ey]+2)%4;
                ex += to[0][back], ey += to[1][back];
            }
            while(!st.empty())
            {
                printf("%c",path[st.top()]);
                st.pop();
            }
            printf("\n");
			return;
		}
		big x = pos.x, y = pos.y;
		for(big i = 0;i < 4;i++)
		{
			big nowx = x+to[0][i], nowy = y+to[1][i]; 
            cout << "P\n";
			if(map[nowx][nowy] != '#' && !vis[nowx][nowy] && map[nowx][nowy] != map[x][y]) 
            {
                q.push(Node({nowx,nowy}));
                ways[nowx][nowy] = i;
				dis[nowx][nowy] = dis[x][y]+1;
				vis[nowx][nowy] = 1;
            }
		}
	}
    printf("-1\n");
}
int main()
{
    scanf("%lld",&T);
    while(T--)
    {
        for(big i = 0;i <= 2001;i++)
        {
            for(big j = 0;j <= 2001;j++)
            {
                dis[i][j] = vis[i][j] = ways[i][j];
                map[i][j] = '#';
            }
        }
        scanf("%lld %lld",&n,&m);
	    for(big i = 1;i <= n;i++)
	    {
	    	scanf("%s",map[i]+1);
	    }  
        bfs(1,1);
        for(big i = 1;i <= n;i++)
        {
            for(big j = 1;j <= m;j++)
            {
                printf("%lld ",dis[i][j]);
            }
            cout << endl;
        }
    }
	return 0;
} 
2024/3/9 22:30
加载中...