DFS
一般像这种只会被遍历一遍的深搜和宽搜时间复杂度都是线性的O(n)
在连通性模型里面
dfs一般是看能否从内部某一个点走到另外一个点,或者问内部哪些点与我们当前这个点是连通的,其实是一个局部的信息
第二种就是,把我们整个部分看成一个整体,然后问我们这个整体能不能变成另外一个整体,也就是,其实它是把我们这个整体当成了一个点,然后,如果我们能变成其他整体的话,就看成是变成了其他的一个点,在这个整体与整体之间,去做一个搜索
举个栗子,就是说这个整体可以看成是一个人,基于连通性的模型是问我们 ,这个人体内部,能否从左手走到右脚
如果是第一种每个点作为一个整体的话,就不需要恢复现场,如果是第二种整体作为一个整体的话,就需要恢复现场,因为第一个要保证每个点只能遍历一遍,第二个要求恢复到之前的状态再找下一个
写dfs的时候一定要注意是不是会爆栈,递归的层数越深的时候,需要的栈空间越大,栈空间默认是1M
如果爆栈就换成BFS或者把DFS的递归改成非递归,这是有一套机械方法的
递归里面的RE经常是爆栈,递归死循环
除了基于连通性的其他的DFS一般是问我们能否从我这个人,比方说传递消息,穿递给另外一个同学
连通性模型
迷宫
感觉Y总的这个代码更简洁
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define endl '\n'
const int N = 110;
char mp[N][N];
bool st[N][N];
int n;
int x1, x2, y1, y2;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
bool dfs(int x, int y)
{
if(mp[x][y] == '#') return false;
if(x == x2 && y == y2) return true;
st[x][y] = 1;
for(int i=0; i<4; i++)
{
int xx = x + dx[i], yy = y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= n || mp[xx][yy] == '#' || st[xx][yy]) continue;
if(dfs(xx, yy)) return true;
}
return false;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
memset(st, 0, sizeof st);
scanf("%d", &n);
for(int i=0; i<n; i++) for(int j=0; j<n; j++) scanf(" %c", &mp[i][j]);
scanf("%d%d", &x1, &y1);
scanf("%d%d", &x2, &y2);
if(dfs(x1, y1)) puts("YES");
else puts("NO");
}
return 0;
}
Flood fill
图和树的遍历
红与黑
一般dfs是这样的这样搜索顺序
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
const int N = 25;
char mp[N][N];
bool st[N][N];
int n, m;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int dfs(int x, int y)
{
int cnt = 1;
st[x][y] = 1;
for(int i=0; i<4; i++)
{
int xx = x + dx[i], yy = y + dy[i];
if(xx < 1 || xx > n || yy < 1 || yy > m || mp[xx][yy] == '#') continue;
if(st[xx][yy]) continue;
cnt += dfs(xx, yy);
}
return cnt;
}
int main()
{
while(cin >> m >> n , n || m)
{
memset(st, 0, sizeof st);
int x1, y1;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
scanf(" %c", &mp[i][j]);
if(mp[i][j] == '@')
{
x1 = i;
y1 = j;
}
}
}
cout << dfs(x1, y1) << endl;
}
return 0;
}