算法基础课(六)——DFS、BFS、图、拓扑排序

2020-05-13   


DFS

去重:str.erase(unique(str.begin(),str.end()),str.end());

需要用栈,空间复杂度与深度成正比 O(h)O(h)

重要概念:回溯和剪枝。每个 DFS 都对应一棵搜索树。

// 数字的全排列
#include <iostream>
using namespace std;
const int N = 10;
int path[N], n;
bool st[N]; // 当前位置是否被用过

void dfs(int u){
    if(u == n) {
        for(int i = 0; i < n; i ++) cout << path[i] << " ";
        cout << endl;
        return;
    }
    for (int i = 1; i <= n; i ++){
        if(!st[i]){
            path[u] = i;
            st[i] = true;
            dfs(u + 1);
            st[i] = false; // 恢复现场
        }
    }
}
int main() {
    cin >> n;
    dfs(0); // 从第 0 个位置开始 dfs,到第 n - 1 个,共 n 个位置
}
// n 皇后
#include <iostream>
using namespace std;
const int N = 20;
char g[N][N], 
int n;
bool col[N], dg[N], udg[N]; // 列和正反对角线是否能放皇后的标记数组

void dfs(int u){
    if(u == n) {
        for(int i = 0; i < n; i ++) cout << g[i] << " ";
        cout << endl;
        return;
    }
    for (int i = 0; i < n; i ++){
        // 过反对角线点的直线方程 i + u = 截距 (y + x = b)
        // 过正对角线点的直线方程 i - u = 截距 (y - x = b) ,由于数组下标要为正,+n 即可,x - y = b 的形式也行。
        if(!col[i] && !udg[i + u] && !dg[i - u + n]){
            g[u][i] = 'Q';
            col[i] = udg[i + u] = dg[i - u + n] = true;
            dfs(u + 1);
            col[i] = udg[i + u] = dg[i - u + n] = false; // 恢复现场
            g[u][i] = '.';
        }
    }
}
int main() {
    cin >> n;
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < n; j ++)
            g[i][j] = '.';
    dfs(0); // 从第 0 行开始 dfs
}
// n 皇后更原始的搜索方案
void dfs(int x, int y, int s){
    // 从 (x, y) 开始搜索,s 表示当前皇后个数
    if(y == n) y = 0, x ++; // 碰到右边界,换行
    if(x == n){
        if(s == n){
            for (int i = 0; i < n; i ++) cout << g[i] << endl;
            cout << endl;
        }
        return;
    }
    // 当前格子不放皇后, 直接搜下一个格子
    dfs(x, y + 1, s);
    // 当前格子放皇后
    if(!row[x] && !col[y] && !udg[y + x] && !dg[y - x + n]){
        g[x][y] = 'Q';
        row[x] = col[y] = udg[y + x] = dg[y - x + n] = true;
        dfs(x, y + 1, s + 1);
        row[x] = col[y] = udg[y + x] = dg[y - x + n] = false;
        g[x][y] = '.';
    }
}
dfs(0, 0, 0);
// 位运算优化
#include <iostream>
using namespace std;

const int N = 20;
int pick[N]; // pick[r] = 0100 表示第 r 行的皇后放到了 i 列
int n;

void dfs(int u, int col, int udg, int dg){
    if(u == n){
        for(int i = 0; i < n; i ++) {
            for(int j = 0 ; j < n; j ++){
                if(pick[i] & (1 << n - 1 - j)) cout << 'Q';
                // if(pick[i] & (1 << j)) 因为对称,1 << 
                else cout << '.';
            }
            cout << endl;
        }
        cout << endl;
        return;
    }
    int pos = ~(col | udg | dg) & ((1 << n) - 1);
    // 后面的 & 是为了高位的 1 变 0
    while(pos) { // pos = 0, 表示没有位置可放了
        pick[u] = (pos & -pos);
        dfs(u + 1, col | pick[u], (udg | pick[u]) << 1, (dg | pick[u]) >> 1);
        pos &= (pos - 1);
    }
    return;    
}

int main() {
    cin >> n;
    
    dfs(0, 0, 0, 0);
}

BFS

需要用队列,空间复杂度是指数级别 O(2h)O(2^h),不过 BFS 是最短路径(边权相等时)。

queue <- 初始状态

while(!queue.empty())

// 迷宫
#include <iostream>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
int n, m;
int g[N][N], d[N][N]; // g 存的是图,d 是每个点到起点的距离
pii q[N * N], pre[N][N]; // pre 是路径数组
int bfs(){
    int hh = 0, tt = -1;
    q[++ tt] = {0, 0}; // 起点入队
    memset(d, -1, sizeof d);
    d[0][0] = 0;
    int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
    while(hh <= tt){
        auto t = q[hh ++];
        for(int i = 0; i < 4; i ++){
            int x = t.first + dx[i], y = t.second + dy[i];
            if(x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] = -1){
                d[x][y] = d[t.first][t.second] + 1;
                pre[x][y] = t;
                q[++ tt] = {x, y};
            }
        }
    }
    int x = n - 1, y = m - 1;
    while(x || y){
        cout << x << ' ' << y << endl;
        auto t = pre[x][y];
        x = t.first, y = t.second;
    }
    return d[n - 1][m - 1];
}
int main() {
    cin >> n >> m;
    for(int i = 0; i < n; i ++)
        for(int j = 0; j < m; j ++)
            cin >> g[i][j];
    cout << bfs() << endl;
}

树与图的存储

树是一种特殊的图。有向图:邻接矩阵,邻接表(类似于拉链哈希)。

// 无权有向图
#include <iostream>
#include <cstring>
using namespace std;

const int N = 100010, M = N * 2;
int n, m;
int h[N], e[M], ne[M], idx; // h 是各点的链表头结点
bool st[N]; // 点是否被搜索过
void dfs(int u){
    st[u] = true;
    for(int i = h[u]; i != -1; i = ne[i]){
        int j = e[i];
        if(!st[j]) dfs(j);
    }
}
void add(int a, int b){// 插入 a 指向 b 的边
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int main() {
    memset(h, -1, sizeof h); 
    dfs(1);// 假定节点 1 开始。
}

树与图的 DFS 和 BFS

// 树的重心
#include <iostream>
#include <cstring>
using namespace std;

const int N = 100010, M = N * 2;
int n;
int h[N], e[M], ne[M], idx; // h 是各点的链表头结点
bool st[N]; // 点是否被搜索过
int ans = N;
int dfs(int u){
    // 以 u 为根的子树中点的数量
    st[u] = true;
    int sum = 1, res = 0; // res 表连通块最大值
    for(int i = h[u]; i != -1; i = ne[i]){
        int j = e[i];
        if(!st[j]) {
            int s = dfs(j);
            res = max(res, s);
            sum += s;
        }
    }
    res = max(res, n - sum);
    ans = min(ans, res);
    return sum;
}
void add(int a, int b){// 插入 a 指向 b 的边
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int main() {
    cin >> n;
    memset(h, -1, sizeof h); 
    for(int i = 0; i < n - 1; i ++){
        int a, b;
        cin >> a >> b;
        add(a, b), add(b, a);
    }
    
    dfs(1);// 假定节点 1 开始。
    cout << ans << endl;
}
// 点的层次
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;
const int N = 100010;

int n, m;
int h[N], e[N], ne[N], idx;
int d[N], q[N], hh, tt = -1;

void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}

int bfs(){
    memset(d, -1, sizeof d); // 初始化距离
    d[1] = 0;
    q[++ tt] = 1;// 第一个节点入队

    while (q.size()){
        int t = q[hh ++];
        for (int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            if (d[j] == -1){
                d[j] = d[t] + 1;
                q[++ tt] = j;
            }
        }
    }
    return d[n];
}

int main(){
    cin >> n >> m;
    memset(h, -1, sizeof h);

    for (int i = 0; i < m; i ++ ){
        int a, b;
        cin >> a >> b;
        add(a, b);
    }
    cout << bfs() << endl;
    return 0;
}

拓扑排序

// 拓扑排序
#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n, m;
int h[N], e[N], ne[N], idx; 
int d[N], q[N], hh = 0, tt = -1; // d 存点的入度

void add(int a, int b){
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}

bool topsort(){
    for (int i = 1; i <= n; i ++ ) if (!d[i]) q[ ++ tt] = i; // 所有没有前驱的节点入队
    while (hh <= tt){
        int t = q[hh ++ ];
        for (int i = h[t]; i != -1; i = ne[i]){
            int j = e[i];
            if (-- d[j] == 0) // d[j] = 0, 说明没有节点指向 j ,j 入队
                q[ ++ tt] = j;
        }
    }

    return tt == n - 1; // 图是否有环
}

int main(){
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 0; i < m; i ++ ){
        int a, b; cin >> a >> b;
        add(a, b);
        d[b] ++ ;
    }
    if (!topsort()) puts("-1");
    else{
        for (int i = 0; i < n; i ++ ) cout << q[i] << " ";
        puts("");
    }
    return 0;
}

Q.E.D.


我是星,利剑开刃寒光锋芒的银星,绝不消隐