This is my blog Ansary's bl|

Ansary

园龄:4年粉丝:0关注:9

dfs题集

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

本文作者:Ansary

本文链接:https://www.cnblogs.com/Ansary/p/15962813.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ansary  阅读(19)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起