0分求助,无法输出!
查看原帖
0分求助,无法输出!
397712
dingyibo楼主2023/7/27 16:36
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>

#define MAX_N 1001

using namespace std;

int n;
int X1, Y1, X2, Y2;
int place[MAX_N][MAX_N];
int offset[4][2] = {{0, -1}, {1, 0}, {-1, 0}, {0, 1}};
bool visits[MAX_N][MAX_N];

struct Point
{
	int x, y;
	int time;
};

int BFS()
{
	queue<Point> q;
	Point p, t;
	p.x = X1;
	p.y = Y1;
	p.time = 0;
	visits[X1][Y1] = true;
	q.push(p);
	
	int x, y, tx, ty;
	
	while(!q.empty())
	{
		p = q.front();
		q.pop();
		
		x = p.x;
		y = p.y;
		
		if(x == X2 && y == Y2)
			return p.time;
		for(int i=0;i<4;++i)
		{
			tx = x + offset[i][0];
			ty = y + offset[i][1];
			
			if(tx >= 1 && tx <= n && ty >= 1 && ty <= n && visits[tx][ty] == false && place[tx][ty] == 0)
			{
				visits[tx][ty] = true;
				t.x = tx;
				t.y = ty;
				t.time = p.time+1;
				q.push(t);
			}
		}
	}
	
	return -1;
}

int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    //cout.tie(0);
	
	int i, j;
	
	cin>>n;
	
	for(i=1;i<=n;++i)
		for(j=1;j<=n;++j)
			cin>>place[i][j];
	
	cin>>X1>>Y1>>X2>>Y2;
	
	cout<<BFS()<<endl;
	
   return 0;
}

2023/7/27 16:36
加载中...