题解
2024-07-15 11:06:17
发布于:上海
**#include<bits/stdc++.h>
using namespace std;
int n,m,sx,sy,ex,ey,k,cnt;
int a[105][105];
int vis[105][105];
int fx[] = {1,0,-1,0};
int fy[] = {0,1,0,-1};
int ansx[205],ansy[205];
struct data{
int x,y,step;
};
int bfs(){
queue<data>q;
q.push({sx,sy,1});
while(q.size()){
data t = q.front();
q.pop();
int x=t.x,y=t.y,step=t.step;
if(x==ex&&y==ey){
return step;
}
for(int i=0;i<4;i++){
int nx = x + fx[i];
int ny = y + fy[i];
if(nx<n&&nx>=0&&ny<m&&ny>=0&&a[nx][ny]!=1&&!vis[nx][ny]){
vis[nx][ny] = 1;
q.push({nx,ny,step+1});
}
}
}
return -1;
}
struct node{
int x,y;
};
void dfs(int x,int y,int step){
if(step>=k){
if(xex && yey){
cnt++;
printf("<%d>-%2d:%d,%d",k,cnt,sx,sy);
for(int i=1;i<step;i++){
printf("-->%d,%d",ansx[i],ansy[i]);
}
cout << endl;
}
return;
}
for(int i=0;i<4;i++){
int nx = x + fx[i];
int ny = y + fy[i];
if(nx<n&&nx>=0&&ny<m&&ny>=0&&a[nx][ny]!=1&&!vis[nx][ny]){
vis[nx][ny] = 1;
ansx[step] = nx;
ansy[step] = ny;
dfs(nx,ny,step+1);
vis[nx][ny] = 0;
}
}
}
int main(){
int t;
cin >> t;
while(t--){
cin >> n >> m;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin >> a[i][j];
if(a[i][j]==2) sx=i,sy=j;
if(a[i][j]==3) ex=i,ey=j;
}
}
memset(vis,0,sizeof(vis));
k = bfs();
//cout << k << endl;
memset(vis,0,sizeof(vis));
cnt = 0;
dfs(sx,sy,1);
}
return 0;
}**
这里空空如也
有帮助,赞一个