首先深搜
先看輸入格式
5 0 1 0 0 0
0 0 0 1 0
0 1 1 0 0
0 0 1 0 1
1 0 0 0 0
第一行輸入乙個數n,接下來輸入n*n的數字矩陣,0代表房間,1代表牆,每個位置都可以往上下左右四個方向走
題意非常簡單,就是求以左上角為出發點所能到達的最多的房間數。
#include
using
namespace
std;
typedef
structpoint;
const
int size = 100+10;
int room[size][size];
int dir[4][2] = ,,,
};int res=0,n;
void dfs(int x,int y)
}}void dfs_stack(int x,int y)}}
}int main()
dfs_stack(1,1);
cout
0;}
再看廣搜,
5 0 1 0 0 0
0 0 0 1 0
0 1 1 0 0
0 0 1 0 1
1 0 0 0 0
輸入格式和第乙個完全一樣,1同樣代表不可以走,但問題不一樣,這個是求從左上角到右下角所需要走的最小的步數。
#include
using
namespace
std;
typedef
structpoint;
const
int size = 100+10;
int room[size][size];
int dir[4][2] = ,,,
};int res=0,n;
int bfs_queue(int x,int y,int m,int n)
room[temp_x][temp_y]=1;
q.pop();
for(int k=0;k<4;k++)}}
if(flag)return steps;
else
return -1;
}int main()
cout
<1,1,n,n)0;}
DFS BFS搜尋 題目
這篇博主寫的是圖的深搜 圖的dfs附 圖的深度優先遍歷 出處 一條魚 2011 12 26 include include struct node 圖頂點結構定義 typedef struct node graph 圖形的結構新型態 struct node head 9 圖形頂點陣列 int vis...
DFS BFS 搜尋訓練
hdu 1016 include include include using namespace std int prime 40 vis 40 num 40 n void checkprime void dfs int i for int c 2 c n c int main return 0 p...
DFS BFS 搜尋總結
做了好多天的搜尋,今天來總結下。dfs 與 bfs dfs 深度優先搜尋 利用棧這種資料結構來實現 利用遞迴便於實現,但是效率較低 找到的第乙個解不一定是最優解,只是先序遍歷最早的可行解。bfs 廣度優先搜尋 利用佇列這種資料結構來實現,找到的第乙個解經常都是最優解 如迷宮的最短路徑 但是不常用來求...