dfs题集
/*************************************************************************
> File Name: 2007.cpp
> Author: Ansary
> Created Time: 2022/3/2 21:24:33
************************************************************************/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int dx[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
char map[6][6];
int ans = 0;
int n;
int vis[6][6];
void dfs(int x, int y, int a, int b){ // dfs的特点就是参数可以根据自己的需要增加,回溯的同时参数也会回溯
if(a == b){
if(ans < a + b)
ans = a + b;
return;
}
for(int i = 0; i < 4; i++){
int nowx = x + dx[i][0];
int nowy = y + dx[i][1];
if(nowx < 0 || nowx >= n || nowy < 0 || nowy >= n || vis[nowx][nowy] == 1)
continue;
if(map[nowx][nowy] == '(' && map[x][y] == ')')
continue;
if(map[nowx][nowy] == '('){
vis[nowx][nowy] = 1;
dfs(nowx, nowy, a + 1, b);
vis[nowx][nowy] = 0;
}
else{
vis[nowx][nowy] = 1;
dfs(nowx, nowy, a, b + 1);
vis[nowx][nowy] = 0;
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
cin >> map[i][j];
vis[0][0] = 1;
if(map[0][0] == '(')
dfs(0, 0, 1 , 0);
cout << ans << endl;
}
本文作者:Ansary
本文链接:https://www.cnblogs.com/Ansary/p/15962813.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步