1.DFS问题
1.1 DFS解决全排列问题
int n = 3;
int path[100];
int st[100];
void dfs(int u) {
if (u == n) {
}
for (int i = 1; i <= n; i++) {
if (!st[i]) {
path[u] = i;
st[i] = true;
dfs(u + 1);
st[i] = false;
}
}
}
void main() {
dfs(0);
}
dfs+回溯;每次结束的时候,完成现场的恢复
1.2 N皇后问题
class Solution {
public:
int col[1000],dg[1000],udg[1000];
vector<vector<string>> res;
int path[1000][1000];
void dfs(int u ,int n){
if(u==n){
vector<string>res_string;
for(int i =0;i<n;i++){
string temp;
for(int j =0;j<n;j++){
temp+=path[i][j];
}
res_string.push_back(temp);
}
res.push_back(res_string);
}
for(int i =0;i<n;i++){
if(!col[i]&&!dg[u+i]&&!udg[n-u+i]){
path[u][i] = 'Q';
col[i] = dg[u+i] = udg[n-u+i] = true;
dfs(u+1, n);
path[u][i] ='.';
col[i] = dg[u+i] = udg[n-u+i] = false;
}
}
}
vector<vector<string>> solveNQueens(int n) {
for(int i =0;i<n;i++){
for(int j=0;j<n;j++){
path[i][j]='.';
}
}
dfs(0,n);
return res;
}
};
2. BFS问题
1. 将起点入队
2. 将队列内 首节点可拓展的节点入队,并将首节点出队
3.重复以上步骤,知道达到目标位置,或者队列为空
2.1 关于迷宫问题
dx[4] = {0,0,-1,1},dy[4]={-1,1,0,0};//上下左右
class Solution {
public:
deque<pair<int,int>>res;
int dx[4] = {0,0,-1,1},dy[4]={-1,1,0,0};
int st[110][110];
int bfs(vector<vector<char>>& maze,vector<int>& entrance,int n,int m){
res.push_back({entrance[0],entrance[1]});
st[entrance[0]][entrance[1]]=0;
while(!res.empty()){
auto item =res.front();
for(int i =0;i<4;i++){
int x = item.first+dx[i],y = item.second + dy[i];
//cout<<x<<" "<<y<<maze[x][y]<< st[x][y]<<endl;
if(0<=x&&x<n&&0<=y&&y<m&&maze[x][y]=='.'&&st[x][y]==-1){
st[x][y]=st[item.first][item.second]+1;
res.push_back({x,y});
if(x==0||x==n-1||y==0||y==m-1){
return st[x][y];
}
}
}
res.pop_front();
}
return -1;
}
int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
memset(st,-1,sizeof st);
int temp = bfs(maze,entrance,maze.size(),maze[0].size());
return temp;
//return 0;
}
};