dfs**:
//// main.cpp
// dfs(迷宮問題自己寫)可輸出搜尋過程
//// created by showlo on 2018/4/14.
//#include #include using namespace std;
#define max_n 102
#define max_m 102
int n,m;
int sx,sy,gx,gy,nx,ny;
char map[max_n][max_m];
int vis[max_n][max_m];
int len,ans,flag;
int dx[4]=,dy[4]=;
int dfs(int x,int y)
else}}
}return len;
}int main() ,dy[4]=;
int bfs(int sx,int sy,int gx,int gy)
{ int nx,ny;
queueq;
memset(direct, inf, sizeof(direct));
q.push(p(sx,sy));
direct[sx][sy]=0;
while (q.size()) {
p q=q.front();
q.pop();
if (q.first==gx&&q.second==gy)
break;
else{
for (int i=0; i<=3; i++) {
nx=q.first+dx[i];
ny=q.second+dy[i];
if (nx<0||nx>n||ny<0||ny>m||map[nx][ny]=='#'||direct[nx][ny]這裡我是用的測試樣例是
5 5s#000
0#0#0
00000
0###0
000#g
用上面兩個**執行可以得到以下結果:
dfs:
5 5s#000
0#0#0
00000
0###0
000#g
1 0
2 0
3 0
4 0
4 1
4 2
2 1
2 2
1 2
0 2
0 3
0 4
1 4
2 4
3 4
4 4
12
program ended with exit code: 0
bfs:
5 5s#000
0#0#0
00000
0###0
000#g
0 0
1 0
2 0
3 0
2 1
4 0
2 2
5 0
4 1
2 3
1 2
5 1
4 2
2 4
0 2
5 2
3 4
2 5
1 4
0 3
5 3
4 4
8
program ended with exit code: 0
可以看出bfs找到的是最短路徑,而dfs找到的路徑則與方向向量的設定有緊密關係,而不一定是最短路徑。
深度優先搜尋DFS(迷宮問題)
問題及 給出迷宮的圖紙和初始終點位置,用dfs求最小步數。include using namespace std int n,m,p,q,min 99999999 int a 51 51 book 51 51 void dfs int x,int y,int step 順時針 右下左上 int tx...
DFS深度優先搜尋 迷宮問題
首先我們用乙個陣列來儲存這個迷宮,用 1 代表障礙物,用 0 代表可通行的路 define n 22 int maze n n 假設我們現在處於 x,y 點 x y 指 maze 陣列的行 列 對於接下來的每一條路徑,我們只能乙個乙個地去嘗試 我們可以先往右走,直到走不通的時候再退回來,然後再去嘗試...
深度優先搜尋(DFS)求解迷宮問題
給乙個n行m列的2維的迷宮,s 表示迷宮的起點,t 表示迷宮的終點,表示不能通過的點,表示可以通過的點。你需要從 s 出發走到 t 每次只能上下左右走動,並且只能進入能通過的點,每個點只能通過一次。現在要求你求出有多少種通過迷宮的的方案。輸入格式 第一行輸入n,m 1 n,m 10 表示迷宮大小。接...