搜索(DFS和BFS)

深搜是我最早学的算法,当然现在还没有信手拈来就是了。。。

为了更好地学树和图,只能回来刷搜索了。。。。。我已经搜了一天了啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊(疯癫)

首先是今天去刷的八皇后问题,特别经典的搜索题,我记得我有一天深夜学算法就看了这个八皇后问题,其实深搜和广搜没有什么模板,就是纯暴力然后标记然后再暴力再标记。。。

调试调试应该没大问题,,,吧。

附上今天八皇后代码:

#include<iostream>
#include<algorithm>
#include<queue>
#include<cmath>
#include<set>
#include<vector>
using namespace std;
#define int long long
#define endl '\n'
const int N = 1e3 + 10, inf = 0x3f3f3f3f3f3f3f3f;
int a[N], rr[N], cc[N], rc[N], cr[N];
int ans, n;
void print() {
    if (ans <= 3) {
        for (int i = 1; i <= n; i++)
            cout << a[i] << " ";
        cout << endl;
    }
}
bool check(int r, int c) {
    if (rr[r] || cc[c] || rc[r + c] || cr[r - c + n])return false;
    rr[r] = 1; cc[c] = 1; rc[r + c] = 1; cr[r - c + n] = 1;
    return true;
}
void cancel(int r, int c) {
    rr[r] = 0; cc[c] = 0; rc[r + c] = 0; cr[r - c + n] = 0;
}
void dfs(int x) {
    for (int i = 1; i <= n; i++) {
        if (check(x, i)) {
            a[x] = i;
            if (x == n) {
                ans++;
                print();
                cancel(x, i);
                return;
            }
            dfs(x + 1);
            cancel(x, i);
        }
    }
}
void solve() {
    cin >> n;
    dfs(1);
    cout << ans;
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    //cin >> t;
    while (t--) solve();
    return 0;
}

一开始在check函数中我用的是stl中的set中的find来标记各种情况,但是最后t了,logn的时间复杂度不过如此。。。

后来发现可以直接用数组,,,我真蠢啊啊啊啊啊啊啊啊啊啊啊啊啊。。。

 

接下来是bfs,一开始这道我是用dfs做的,结果,样例都过不了,后来自习观察了一下,发现是一道bfs。。。我是真的菜。。。。

马的遍历,上代码:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
const int N = 1e3 + 10, inf = 0x3f3f3f3f3f3f3f3f;
int a[N][N], nextt[8][2] = { {2,1},{-2,1},{-2,-1},{2,-1},{1,2},{1,-2},{-1,-2},{-1,2} };
bool book[N][N];
void bfs(int n,int m,int x,int y) {
    queue<pair<int,int>> q;
    q.push(make_pair(x,y));
    while (!q.empty()) {
        x = q.front().first, y = q.front().second;
        q.pop();
        for (int i = 0; i < 8; i++) {
            int tx = x + nextt[i][0], ty = y + nextt[i][1];
            if (book[tx][ty] || tx > n || ty > m || tx < 1 || ty < 1)continue;
            book[tx][ty] = true;
            a[tx][ty] = a[x][y] + 1;
            q.push(make_pair(tx, ty));
        }
    }
}
void solve() {
    int n, m, x, y;
    cin >> n >> m >> x >> y;
    memset(a, -1, sizeof(a));
    memset(book, false, sizeof(book));
    book[x][y] = true;
    a[x][y] = 0;
    bfs(n,m,x,y);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++)
            cout << a[i][j] << " ";
        cout << endl;
    }
}
signed main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    //cin >> t;
    while (t--) solve();
    return 0;
}

突然发现bfs的代码和dijkstra的优先队列法有点一样???所以dijkstra是用bfs哦!!!!!!!!!!!!我个sb,写了那么久bfs,现在才发现那是bfs。。。

posted @ 2023-07-31 21:14  DLSQS  阅读(45)  评论(0)    收藏  举报