Computer Game

题目:

Monocarp is playing a computer game. Now he wants to complete the first level of this game.

A level is a rectangular grid of 2 rows and n columns. Monocarp controls a character, which starts in cell (1, 1) — at the intersection of the 1-st row and the 1-st column.

Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell (x1​,y1​) to cell (x2​,y2​) in one step if |x1 - x2|≤1 and∣y1​−y2​∣≤1. Obviously, it is prohibited to go outside the grid.

There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.

To complete a level, Monocarp's character should reach cell (2, n) — at the intersection of row 2 and column n.

Help Monocarp determine if it is possible to complete the level.

Input

The first line contains a single integer t (1≤t≤100) — the number of test cases. Then the test cases follow. Each test case consists of three lines.The first line contains a single integer n 

(3≤n≤100) — the number of columns.The next two lines describe the level. The i-th of these lines describes the i-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell.

Additional constraint on the input: cells (1,1) and (2,n) are safe.

Output

For each test case, output YES if it is possible to complete the level, and NO otherwise.

思路:

题目大意:也是一个走迷宫的问题,给出一个迷宫,问是否可以从起点走到终点。这里用0表示空地,用1表示墙壁,方向为八个方向。

而本题的问题是“能否到达”,所以本题解决的方法是dfs。

dfs实现的方式是递归;

代码: 

#include<bits/stdc++.h>//万能头;
using namespace std;
int v[2][105];//记录该状态是否出现的数组;
int dx[8]={-1,0,1,-1,1,-1,0,1};
int dy[8]={-1,-1,-1,0,0,1,1,1};
//表示方向;
bool dfs(char a[][105],int sx,int sy,int ex,int ey)
{
	int i;
	if(sx==ex&&sy==ey)
	return true;
//判断是否到达终点;
	for(i=0;i<8;i++)
	{
		int tx=sx+dx[i];
		int ty=sy+dy[i];
		v[sx][sy]=1;
		if(tx>=0&&tx<2&&ty>=0&&ty<ey+1&&a[tx][ty]!='1'&&v[tx][ty]!=1&&dfs(a,tx,ty,ex,ey))
        //判断下一个状态是否合法;
        //即是否在棋盘的范围之内,是否访问过,如果满足,就进行下一个状态的判断,由此形成递归;
		return true;
        //如果以上状态都满足,即最终这一条分支可以到达终点,返回真;
	}
	return false;
    //表示碰到了死路,返回假;
}
int main(){
	int t,n,i;
	scanf("%d",&t);
	while(t--)
	{
		memset(v,0,sizeof(v));
		scanf("%d",&n);
		char a[2][105];
		for(i=0;i<2;i++)
			scanf("%s",a[i]);
		if(dfs(a,0,0,1,n-1))
        //如果最终的返回值是真,则可以到达终点;
		printf("YES\n");
		else
        //如果是假,表示没有一条路到达终点;
		printf("NO\n");
	} 
	return 0;
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值