生活随笔
收集整理的這篇文章主要介紹了
不止代码:迷宫问题(bfs)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
如下圖所示,給出一個N*M的迷宮圖和一個入口、一個出口。
編一個程序,打印一條從迷宮入口到出口的路徑。這里黑色方塊的單元表示走不通(用-1表示),白色方塊的單元表示可以走(用0表示)。只能往上、下、左、右四個方向走。如果無路則輸出“no way.”。
分析
可以用bfs和dfs兩種思路;
bfs
比較好寫
用一個類似于鏈式前向星的思路回溯輸出
dfs
也很好寫。。。
傳一個step用于記錄輸出
連鏈式前向星都不用了
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#define ll long long
using namespace std
;
int mp
[1001][1001];
int m
,n
;
int lastx
[1001][1001],lasty
[1001][1001];
int xx0
,yy0
,X
,Y
;
int dx
[5]={0,0,0,1,-1},dy
[5]={0,1,-1,0,0};
struct node
{int x
,y
;
};
int jd
[1001][1001];
int ansx
[3001],ansy
[3001];
void print(){int px
=X
,py
=Y
,num
=0;ansx
[++num
]=X
,ansy
[num
]=Y
;while(px
!=xx0
||py
!=yy0
){ansx
[++num
]=lastx
[px
][py
];ansy
[num
]=lasty
[px
][py
];int ex
=px
;px
=lastx
[px
][py
];py
=lasty
[ex
][py
];}ast
for(int i
=num
;i
>=1;i
--){printf("%d,%d\n",ansx
[i
],ansy
[i
]);}return;
}
void bfs(){queue
<node
>q
;q
.push((node
){xx0
,yy0
});while(!q
.empty()){node o
=q
.front();q
.pop();if(o
.x
==X
&&o
.y
==Y
){print();return;}
for(int i
=1;i
<=4;i
++){int nx
=o
.x
+dx
[i
],ny
=o
.y
+dy
[i
];if(nx
<1||nx
>n
||ny
<1||ny
>m
||jd
[nx
][ny
]||mp
[nx
][ny
]==-1) continue;lastx
[nx
][ny
]=o
.x
;lasty
[nx
][ny
]=o
.y
;q
.push((node
){nx
,ny
});jd
[nx
][ny
]=1;
}}printf("no way");
}
int flag
=0,ans
;
void print2(){for(int i
=1;i
<=ans
;i
++){printf("%d,%d\n",ansx
[i
],ansy
[i
]);}return;
}
void dfs(int x
,int y
,int step
){if(x
<1||x
>n
||y
<1||y
>m
||jd
[x
][y
]||mp
[x
][y
]==-1) return;
if(x
==X
&&y
==Y
){flag
=1;ansx
[step
]=x
;ansy
[step
]=y
;ans
=step
;return;}jd
[x
][y
]=1;for(int i
=1;i
<=4;i
++){dfs(x
+dx
[i
],y
+dy
[i
],step
+1);if(flag
){ansx
[step
]=x
;ansy
[step
]=y
;if(step
==1) print2();return;}}
}
int main(){scanf("%d%d",&n
,&m
);for(int i
=1;i
<=n
;i
++){for(int j
=1;j
<=m
;j
++){scanf("%d",&mp
[i
][j
]);}}scanf("%d%d%d%d",&xx0
,&yy0
,&X
,&Y
);
dfs(xx0
,yy0
,1);return 0;
}
總結
以上是生活随笔為你收集整理的不止代码:迷宫问题(bfs)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。