浅学一下DFS和BFS,解决全排列和迷宫问题

DFS

全排列

原题链接:https://www.acwing.com/problem/content/844/

  • 超过边界return
  • 循环遍历,如果已经访问过则continue
  • 标记访问过
  • 递归下一层
  • 回溯清空
#include <stdio.h>
#include <iostream>

using namespace std;

int n;
int path[10];
bool st[10] = {false} ;

void DFS(int x)
{
    if(x > n)
    {
        for (int i = 1; i <= n; i++)
            cout << path[i] << " ";
        cout << endl;
        return;
    }

    for(int i = 1; i <= n; i++)
    {
        if(st[i] == true)
            continue;
        path[x] = i;
        st[i] = true;
        DFS(x + 1);
        st[i] = false;
    }

}

int main()
{
    cin >> n;
    DFS(1);
    return 0;
}

BFS

迷宫问题

原题链接:https://www.acwing.com/problem/content/846/

  • 设计一个队列
  • 把初始点加入到队列中
  • while(q.size())
  • 弹出队列的首元素
  • 上下左右四个方向遍历
  • 如果在范围内,就把该结点放到队列中,距离是上一个结点+1
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>

using namespace std;

int n,m;
int map[105][105];
int rec[105][105];
int xx[4] = {-1,0,1,0};
int yy[4] = {0,1,0,-1};
int hh = 0;
int tt = 0;
typedef pair<int,int> PII;



int bfs()
{
    queue<PII> q;
    rec[1][1] = 0;
    q.push({1,1});
    while(q.size())
    {
        auto t = q.front();
        q.pop();

        for(int i = 0 ; i < 4; i++)
        {
            int x = t.first + xx[i];
            int y = t.second + yy[i];
            if(x < 1 || x > n || y < 1 || y > m || map[x][y] == 1 || rec[x][y] != 0)
                continue;
            q.push({x,y});
            rec[x][y] = rec[t.first][t.second] + 1;
        }

    }
    return rec[n][m];
}

int main()
{
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j<= m; j++)
            cin >> map[i][j];
    }
    cout << bfs() << endl;
}

posted @ 2022-08-12 17:37  火车驶向云外0218  阅读(89)  评论(0)    收藏  举报