DFS在求解连通性时有很好的应用,而且代码会比BFS简洁
DFS求解有两种,图内连通和图外连通。图内联通是图内的两个点连通,每个点只需遍历一次,而图外连通是指求解图状态改变的连通,如求解最短路径,每个点可能遍历多次,这时需要恢复现场,进行回溯
AcWing 1112. 迷宫
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int sa, sb, ea, eb;
int n;
int bx[] = {1,-1,0,0};
int by[] = {0,0,1,-1};
char a[110][110];
int st[110][110];
bool dfs(int x, int y)
{
//cout << x << " " << y << endl;
if(x < 1 || x > n || y < 1 || y > n)return false;
if(st[x][y])return false;
if(a[x][y] == '#') return false;
if(x == ea + 1 && y == eb + 1)return true;
st[x][y] = true;
for(int i = 0; i < 4; i ++ )
{
int nx = x + bx[i], ny = y + by[i];
if(dfs(nx, ny))return true;
}
return false;
}
int main()
{
int t;
cin >> t;
while(t--)
{
memset(st, 0, sizeof st);
cin >> n;
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= n; j ++ )
{
cin >> a[i][j];
}
cin >> sa >> sb >> ea >> eb;
if(dfs(sa + 1,sb + 1))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
AcWing 1113. 红与黑
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char g[22][22];
int st[22][22];
int bx[] = {0,0,1,-1};
int by[] = {1,-1,0,0};
int n,m;
int sa, sb;
int dfs(int x, int y)
{
int ans = 0;
st[x][y] = true;
for(int i = 0; i < 4; i ++ )
{
int a = x + bx[i], b = y + by[i];
if(a < 1 || b < 1 || a > n || b > m)continue;
if(st[a][b])continue;
if(g[a][b] == '#')continue;
ans += dfs(a,b) + 1;
}
return ans;
}
int main()
{
while(true)
{
cin >> m >> n;
if(!n)break;
memset(st, 0, sizeof st);
for(int i = 1; i <= n; i ++ )
for(int j = 1; j <= m; j ++ )
{
cin >> g[i][j];
if(g[i][j] == '@')
sa = i, sb = j;
}
cout << dfs(sa, sb) + 1 << endl;
}
}