Is It a Snake


Problem Statement :


One day I was visiting a temple in which snakes were worshiped. I happened to find a golden plate of dimension 2 * n in it. It had 2 rows of n cells each, and so the total number of cells is 2 * n. Each cell of the plate was either white or black, denoted by '.' and '#' respectively. Legend says that a snake was lying on this plate for many years and prayed. So, the cells that were covered by its body have turned black, the rest of the cells were white. Its entire body was supposedly on this plate. Also, you know that a snake likes to make itself comfortable, so none of its parts will be intersecting with its other parts.

Usually, I am skeptical of such legends. So, I want to check for myself whether the legend could potentially be true or not. For example, consider the golden plate given below:


##
##

Now, the legend could be true. A snake can be on it, and one possible configuration is as follows. The head of the snake is at (1, 1), then the next portion at (1, 2), then at (2, 2) and then the finally the tail at (2, 1). Notice that the parts of the snake can be adjacent only if the corresponding cells have a common side.

##.#..
.###..

There can be a snake on the plate above.


##.##
.#.#.
The legend is surely false if the plate is as above. These are not marks of a single snake. There could be more than one possible snakes here. But not a single snake.

Given the description of the plate, figure out if the legend could be true, or if it is definitely false.

Input

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.

The first line of each test case contains an integer n.

The next two lines each contain n characters denoting the rows of the plate.

Output

For each test case, output a single line containing "yes" or "no" (without quotes) corresponding to the answer of the problem.

Constraints
1 ≤ T ≤ 500
1 ≤ n ≤ 500
There will be at least one cell containing the character '#'

Example

Input
6
2
##
..
2
##
.#
2
#.
.#
7
#.###..
#######
6
##.#..
.###..
5
##.##
.#.#.

Output
yes
yes
no
no
yes
no



Solution :



title-img


                            Solution in C :

#include <stdio.h>
#define BLACK 0
#define WHITE 1
int main()
{
    int cases,n,i,j,start,end,prev,next;
    char c;
    scanf("%d",&cases);
    label:
    while(cases--)
    {
        scanf("%d\n",&n);
        int a[2][n];
        for(i=0;i<2;i++)
        {
            for(j=0;j<n;j++)
            {
                scanf(" %c",&c);
                a[i][j]=(c=='.')?WHITE:BLACK;
            }
        }
        for(i=0;1;i++)
            if(a[0][i]==BLACK || a[1][i]==BLACK)
            {
                start=i;
                break;
            }
        for(i=n-1;1;i--)
            if(a[0][i]==BLACK || a[1][i]==BLACK)
            {
                end=i;
                break;
            }
        for(i=start;i<=end;i++)
            if((a[0][i] == WHITE) && a[1][i]==WHITE)  
            {                                           
                printf("no\n");
                goto label;
            }
        for(i=start+1;i<=end;i++)      
        {                              
            if( (a[0][i]==BLACK && a[1][i-1]==BLACK) &&    (a[0][i-1]==WHITE && a[1][i]==WHITE)    )
            {
                printf("no\n");
                goto label;
            }
            if( (a[0][i]==WHITE && a[1][i-1]==WHITE) &&    (a[0][i-1]==BLACK && a[1][i]==BLACK)    )
            {
                printf("no\n");
                goto label;
            }
        }
        for(i=start;i<=end;i++)
        {
            if((a[0][i] == a[1][i]) && a[1][i]==BLACK)
            {
                if(start==i)
                {
                    while(a[0][i]==BLACK && a[1][i]==BLACK)
                        i++;
                }
                else
				{
                int rectlength=0;
                prev=(a[0][i-1]==BLACK)?0:1;
                while((a[0][i] == a[1][i]) && a[1][i]==BLACK)
                {
                    if(i==end)
                    {
                        printf("yes\n");
                        goto label;
                    }
                    rectlength++;
                    i++;
                }
                if(rectlength%2==0 )
                {  
                    if(a[prev][i]==WHITE)
                    {
                        printf("no\n");
                        goto label;
                    }
                }
                else
                {
                    if(a[prev][i]==BLACK)
                    {
                        printf("no\n");
                        goto label;
                    }
                }
                }
            }
        }
        printf("yes\n");
    }
}
                        


                        Solution in C++ :

#include <bits/stdc++.h>

#define I_O ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

//~~~~~~~~~~~~ Sort Form Of Long~~~~~~~~~~~//
#define ll long long int
#define lls int64_t
#define ld long double
#define db double
#define ull unsigned long long int

//~~~~~~~~~~~~~~Pair~~~~~~~~~~~~~~~~~~//
#define pii pair<int, int>
#define pll pair<lls, lls>
#define pdd pair<db,db>
#define psi pair<string,int>
#define vi vector<int>
#define vl vector<lls>
#define vd vector<db>
#define vs vector<string>
#define vb vector<bool>
#define vpi vector<pii>
#define vpl vector<pll>
#define vpd vector<pdd>
#define vpsi vector<psi>
#define vvi vector<vector<int>>

//~~~~~~~~~~~~~~Vector~~~~~~~~~~~~~~~~~//
#define pb push_back
#define pf push_front
#define MP make_pair
#define in insert
#define ff first
#define ss second
#define al(v) v.begin(),v.end()
#define alr(v) v.rbegin(), v.rend()
#define srt(v) sort(al(v))
#define srtr(v) sort(al(v), greater<int>());
#define len(x) ((int)(x).size())
#define rev(v) reverse(al(v))
#define btcnt(n) __builtin_popcount(n)
#define acl(v, n) accumulate(al(v), n)
#define eb emplace_back
#define Lrt(s, c) rotate(s.begin(), s.begin() + c, s.end())
#define Rrt(s, c) rotate(s.begin(), s.begin() + s.size() - c, s.end())
#define lb(v, kk) lower_bound(al(v), kk) - v.begin()
#define ub(v, kk) upper_bound(al(v), kk) - v.begin()
#define tpu(str) transform(al(str), str.begin(), ::toupper)
#define tpl(str) transform(al(str), str.begin(), ::tolower)
#define cignr cin.ignore(numeric_limits<streamsize>::max(), '\n');
#define mxv(v) *max_element(al(v))
#define mnv(v) *min_element(al(v))

const int MOD = 1e9 + 7;
const lls INF = 2e18;
const int mxn = 2e9 + 9;
const int mxd = 2e5 + 5;
const int mxa = 2e6 + 5;

//~~~~~~~~~~~~~~~~~~Function~~~~~~~~~~~~~~~~~~~~//
lls gcd(lls a, lls b){ if(b == 0LL) return a; return gcd(b, a % b); }
lls lcm(lls a, lls b){ return (a / gcd(a, b) * b); }
lls maxll(lls x, lls y){ return x > y ? x : y; }
lls minll(lls x, lls y){ return x < y ? x : y; }

//~~~~~~~~~~~~~~~Loops and Short~~~~~~~~~~~~~~~~//

#define PI acos(-1)
#define Cn continue
#define Br break
#define off return 0
#define N '\n'
#define fopen freopen("input.txt", "r", stdin);
#define rep(i, n) for(lls i = 0; (lls)i < n; i++)
#define repn(i, a, b) for(lls i = (lls)(a); i < (lls)(b); i++)
#define repr(i, a, b) for(lls i = (lls)(a) - 1; i >= (lls)(b); i--)
#define test_case() int T; cin >> T; while(T--)

using namespace std;

// ===================================~~~~~~ SOLUTION STARTS HERE ~~~~~~=================================== //

//int a, b, c, d, e, res = 0, ans = 0, prod = 1, n, m, cnt = 0, k, l, r, s, t, x, y, f, i, j, p;

char a[2][501];
bool vis[2][502];

bool dfs(int k, int n, int j) {
   bool ans = true;
   memset(vis, 0, sizeof(vis));

   for (int i = j; i < n; i++) {
      if (a[k][i] == '#') {
         vis[k][i] = 1;
         if (k == 0) {
            if (a[k + 1][i] == '#') {
               vis[++k][i] = true;
            }
         } else {
            if (a[k - 1][i] == '#') {
               vis[--k][i] = true;
            }
         }
      } else break;
   }

   for (int i = 0; i < n; i++) {
      if (a[0][i] == '#' and !vis[0][i]) {
         ans = false; break;
      }

      if (a[1][i] == '#' and !vis[1][i]) {
         ans = false; break;
      }
   }

   return ans;
}

void Run_Case() 
{
   int n, b, f, g;
   cin >> n;
   rep (i, n) cin >> a[0][i];
   rep (i, n) cin >> a[1][i];

   int cnt = 0;

   for (int i = 0; i < n; i++) {
      if (a[0][i] == '#' or a[1][i] == '#') {
         b = i; break;
      }
   }

   f = dfs(0, n, b);
   g = dfs(1, n, b);

   if ((f + g) != 0) cout << "yes\n";
   else cout << "no\n";
}

int main()
{
   I_O
   test_case()
   {
      Run_Case();
   }

   off;
}
                    


                        Solution in Java :

import java.io.*;
import java.util.*;

class ISSNAKE {
    public static void main (String[] args)  throws IOException  {
        Scanner sc= new Scanner(System.in);
         while (sc.hasNextLine())
            {
             
        int t = Integer.parseInt( sc.nextLine() );
        testcase:
        for ( int z = 0; z < t; z++ ) {
            int n = Integer.parseInt( sc.nextLine() );
            char[][] snake = new char[2][n];
            snake[0] = sc.nextLine().toCharArray();
            snake[1] = sc.nextLine().toCharArray();
            boolean[] s1 = new boolean[n];
            boolean[] s2 = new boolean[n];
            int start = 0;
            while ( snake[0][start] == '.' && snake[1][start] == '.' )
                start++;
            s1[start] = snake[0][start] == '#';
            s2[start] = snake[1][start] == '#';
            boolean ended = false;
            for ( int i = start + 1; i < n; i++ ) {
                if ( snake[0][i] == '#' && snake[1][i] == '#' ) {
                    s1[i] = s2[i - 1];
                    s2[i] = s1[i - 1];
                }
                else if ( snake[0][i] == '#' ) {
                    s1[i] = s1[i - 1];
                }
                else if ( snake[1][i] == '#' ) {
                    s2[i] = s2[i - 1];
                }
                if ( ! s1[i] && ! s2[i] )
                    ended = true;
                if ( ended && ( snake[0][i] == '#' || snake[1][i] == '#' ) ) {
                    System.out.println( "no" );
                    continue testcase;
                }
            }
        
            System.out.println( "yes" );
          }
        }
    }
}
                    


                        Solution in Python : 
                            
def strtolist(a:str):
    b = []
    for i in range(0, n):
        b.append(a[i])
    return b

def mainthing():
    p = -1
    l = 0
    for i in range(0, n * 2):
        if p == -1:
            if l1[i] == '#':
                p = i
                l = 1
                l1[p] = 0
            elif l2[i] == '#':
                p = i
                l = 2
                l2[p] = 0
        else:
            if l == 1:
                if l2[p] == '#':
                    l = 2
                    l2[p] = 0
                elif p != n - 1 and l1[p + 1] == '#':
                    p += 1
                    l1[p] = 0
                else:
                    break
            elif l == 2:
                if l1[p] == '#':
                    l = 1
                    l1[p] = 0
                elif p != n - 1 and l2[p + 1] == '#':
                    p += 1
                    l2[p] = 0
                else:
                    break

t = int(input())

for j in range(0, t):
    n = int(input())
    a = str(input())
    l1 = strtolist(a)
    l1b = strtolist(a)
    a = str(input())
    l2 = strtolist(a)
    l2b = strtolist(a)
    
    mainthing()

    # This part checks if there are any black tiles left.
    r = False
    for i in range(0, n):
        if l1[i] == '#' or l2[i] == '#':
            r = True
            break

    l1 = l2b
    l2 = l1b
    
    mainthing()

    # This part checks if there are any black tiles left.
    r2 = False
    for i in range(0, n):
        if l1[i] == '#' or l2[i] == '#':
            r2 = True
            break
    
    if not r or not r2:
        print('yes')
    else:
        print('no')
                    


View More Similar Problems

Array-DS

An array is a type of data structure that stores elements of the same type in a contiguous block of memory. In an array, A, of size N, each memory location has some unique index, i (where 0<=i<N), that can be referenced as A[i] or Ai. Reverse an array of integers. Note: If you've already solved our C++ domain's Arrays Introduction challenge, you may want to skip this. Example: A=[1,2,3

View Solution →

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →