U-Turn (深搜)

Given the map of a town with R x C cells, and each cell is:

X: building segment
.: a road surface

Each turn, you can move (up, down, left, or right) from a road surface to the neighboring road surface.

Now, you start from any possible road surface cells as the starting cell, and move to any possible directions, can you return to the starting cell without making a 180 degrees turn (U-turn)?

input

The first line contains two positive integers R and C (3 ≤ R, C ≤ 10).
Then follows R lines, each line has C characters, each is either “X” or “.”, representing each cell of the map.
There are at least two "." and all "." characters are connected into some roads.

output

Output 0 if you can return to the starting cell for any moves without making a 180 degrees turn. Otherwise output 1.

sample input

4 3
XXX
X.X
X.X
XXX

sample output

1

attention

Another case:

4 4
XXXX
X..X
X..X
XX.X
You should output 1 because if you start from any of the road surface cell and move to the 4th row and the 3rd column cell, then you can not return back.

题意:在一个所给的地图中,一辆不会拐弯的车能不能行驶回到出发点。

分析:一看到这样的题目,基本上就是深搜的做法,这道题目用深搜可以解决,还有一个比较特殊的做法也可以ac.

普通的深度搜索

#include<stdio.h>
char str[15][15];
char mod[15][15];
int n,m,flag=1;
int e=0;
void modle()
{
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			mod[i][j]=str[i][j];
		}
	}
}
int dfs(int i,int j)
{
	e++;
    if(e>2&&(mod[i+1][j]=='?'||mod[i-1][j]=='?'||mod[i][j+1]=='?'||mod[i][j-1]=='?'))
    flag=0;
    if(mod[i][j]!='?')
    mod[i][j]='X';
    if(mod[i+1][j]=='.')
    {
        dfs(i+1,j);
    }
    if(mod[i-1][j]=='.')
    {
        dfs(i-1,j);
    }
    if(mod[i][j-1]=='.')
    {
        dfs(i,j-1);
    }
    if(mod[i][j+1]=='.')
    {
        dfs(i,j+1);
    }
}
int main()
{
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
	{
		scanf("%s",str[i]);
	}
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(str[i][j]=='.')
			{
				modle();
				mod[i][j]='?';
				dfs(i,j);
                if(flag==1)
                {
                    printf("1\n");
                    return 0;
                }	
				flag=1;	
				e=0;		
			}
		}
	}
	printf("0\n");
	return 0;
}

特殊的解决办法

#include<cstdio>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
char map[12][12];
int dfs(int r,int c)
{
	int flag=0;
	for(int i=1;i<=r;i++)
	{
		for(int j=1;j<=c;j++)
		{
			int sum=0;
			if(map[i][j]=='.')
			{
				if(map[i-1][j]=='.')
				sum++;
				if(map[i+1][j]=='.')
				sum++;
				if(map[i][j-1]=='.')
				sum++;
				if(map[i][j+1]=='.')
				sum++;
				if(sum==1)
				flag=1;
			}
		}
	}
	return flag;
}
int main()
{
	int i,j,r,c;
	scanf("%d %d",&r,&c);
	for(i=1;i<=r;i++)
	{
		getchar();
		for(j=1;j<=c;j++)
		scanf("%c",&map[i][j]);
	}
	printf("%d\n",dfs(r,c));
} 


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值