10. DFS +BFS

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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋进在AI路上的小李

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值