codeforces 1234C Pipes (dfs)

题目链接:https://codeforces.com/problemset/problem/1234/C

直接dfs
管道分为两种
只可能向上/下/右方向走,把边界范围限制好

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
typedef long long ll;

const int maxn = 200010;

int q,n,f;
int t[3][maxn];
char s1[maxn],s2[maxn];

void dfs(int x,int y,int dir){ // dir 1上/ 2下/ 3右 
	if(x<=0 || (y<=0 && x!=1) || (y>=n+1 && x!=2) || x>=3){
		return;
	}
	if(x==2 && y==n+1){
		printf("YES
");
		f = 1;
		return;
	}
	if(t[x][y] == 1){
		if(dir == 2 || dir == 1) return;
		else {
			dfs(x,y+1,3);
		}
	}
	else if(t[x][y] == 2){
		if(dir == 2 || dir == 1){
			dfs(x,y+1,3);
		}
		else if(dir == 3){
			dfs(x-1,y,1);
			dfs(x+1,y,2);
		}
	}
}

ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }

int main(){
	q = read();
	while(q--){
		f = 0;
		n = read();
		scanf("%s",s1);
		scanf("%s",s2);
		for(int i=0;i<n;++i){
			if(s1[i] == '1' || s1[i] == '2') t[1][i+1] = 1;
			else t[1][i+1] = 2;
			if(s2[i] == '1' || s2[i] == '2') t[2][i+1] = 1;
			else t[2][i+1] = 2;
		}
		
		if(t[1][1] == 1) dfs(1,2,3);
		else{
			dfs(2,1,2);
		}
		if(!f){
			printf("NO
");
		}
	}
	
	return 0;
}
原文地址:https://www.cnblogs.com/tuchen/p/13822473.html