算法引入:
严格来说,搜索算法也算是一种暴力枚举策略,但是其算法特性决定了效率比直接的枚举所有答案要高,因为搜索可以跳过一些无效状态,降低问题规模。在算法竞赛中,如果选手无法找到一种高效求解的方法(比如贪心、递推、动态规划、公式推导等),使用搜索也可以解决一些规模较小的情况;而有的任务就是必须使用搜索来完成,因此这是相当重要的策略。
深度优先搜索:
从一个点一直往下搜,直到不能搜为止。
算法模板:
int dfs(int u)
{
st[u] = true; // st[u] 表示点u已经被遍历过
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j]) dfs(j);
}
}
经典样例:八皇后问题
基本思路:
首先明确每行只能有一个皇后,所以只需要用BFS枚举每行皇后所在的列数即可,并且要创建vis数组来记录之前这一行和对角线是否纯在其他皇后。
代码实现:
#include <iostream>
#include <algorithm>
using namespace std;
int a[15] = {0}, n, cnt = 0;
void dfs(int cur) {
if (cur == n + 1) {
cnt++;
if (cnt <= 3) {
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
cout << "\n";
}
return;
}
for (int i = 1; i <= n; i++) {
a[cur] = i;
int st = 1;
for (int j = 1; j < cur; j++)
if (a[cur] == a[j] ||
a[cur] + cur == a[j] + j || //a[x] + x 表示某一斜对角线的标记值
a[cur] - cur == a[j] - j) { //a[x] - x 表示某一正对角线的标记值
st = 0;
break;
}
if (st)
dfs(cur + 1);
}
}
int main(void) {
cin >> n;
dfs(1);
cout << cnt;
return 0;
}
洛谷练习题:
P2392 kkksc03考前临时抱佛脚 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1596 [USACO10OCT] Lake Counting S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
广度优先搜索:
模拟队列,把当前状态所有情况入队,再往深搜索。
算法模板:
queue<int> q;
st[1] = true; // 表示1号点已经被遍历过
q.push(1);
while (q.size())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
st[j] = true; // 表示点j已经被遍历过
q.push(j);
}
}
}
经典样例:马的遍历
基本思路:
使用BFS,对于走到的每一个点,把接下来能走的点全部枚举出来,并用vis数组标记,这样会先求到最短路,比DFS枚举每一条线路的效率更高。
代码实现:
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int N = 405;
int d[N][N], n, m, x, y;
typedef pair<int, int> PII; \\下面是表示方向的数组
int dr[8] = {1, 1, -1, -1, 2, 2, -2, -2}, dc[8] = {2, -2, -2, 2, 1, -1, -1, 1};
void bfs(int r, int c) {
queue<PII> q;
q.push({r, c});
d[r][c] = 0;
while (q.size()) {
auto t = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
int x = t.first + dr[i], y = t.second + dc[i];
if (d[x][y] == -1 && x >= 1 && x <= n && y >= 1 && y <= m) {
d[x][y] = d[t.first][t.second] + 1;
q.push({x, y});
}
}
}
}
int main(void) {
memset(d, -1, sizeof d);
cin >> n >> m >> x >> y;
bfs(x, y);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
cout << d[i][j] << " ";
cout << endl;
}
return 0;
}
洛谷练习题:
P1135 奇怪的电梯 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
P1825 [USACO11OPEN] Corn Maze S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)