Acwing 2005

/*************************************************************************
> 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;
}