参考文献
Click me
DFS经典例题
排列数字
#include <bits/stdc++.h>
using namespace std;
int ans[10];
bool st[10];
int n;
void dfs(int u){
if(u==n){//返回条件
for(int i = 0;i < n;i++){
cout << ans[i] << " ";
}
cout<<endl;
return;
}
for(int i = 1;i <= n;i++){//从头到尾开始dfs
if(st[i] == false){
st[i] = true;
ans[u]=i;
dfs(u+1);
//复原
st[i] = false;
ans[u] = 0;
}
}
}
int main(){
cin >> n;
dfs(0);
}
BFS经典例题
走迷宫
#include <bits/stdc++.h>
using namespace std;
int n,m;
const int N = 110;
int mp[N][N];
int mark[N][N];
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
bool check(int x,int y){
return (x>=0&&x<n&&y>=0&&y<m);
}
void bfs(){
memset(mark,-1,sizeof mark);//初始化所有的mark为-1,方便统计哪个没走过
queue<pair<int,int>> q;//创建一个队列,至于为什么,参考文献里有
q.push({0,0});//加入起点
mark[0][0] = 0;
while(q.size()){//不断遍历直到队列为空(遍历完)
auto t = q.front();//取出队头元素
for(int i = 0;i < 4;i++){//通过方向向量对四周可以扩散的地方进行扩散
int nx = t.first + dx[i];
int ny = t.second + dy[i];
if(check(nx,ny)&&mark[nx][ny]==-1 && mp[nx][ny]==0){//如果没超出边界且没走过且可以走就走
mark[nx][ny] = mark[t.first][t.second]+1;//累加步数
q.push({nx,ny});//在队列中加入这个点
}
}
q.pop();//弄完就取出
}
cout << mark[n-1][m-1];
}
int main(){
cin >> n >> m;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cin >> mp[i][j];//输入迷宫
}
}
bfs();
}