TZOJ4481: U-Turn(深搜)

TZOJ4481: 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)?

输入

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 0 if you can return to the starting cell for any moves without making a 180 degrees turn. Otherwise output 1.

样例输入
4 3
XXX
X.X
X.X
XXX
样例输出
1
解题思路

题目要求我们从任何一点向上下左右四个方向出发不能回头并最终回到起点,则称为没有死胡同。按题意深搜即可,写的时候一直以为是不能向上走。。

代码
#include<bits/stdc++.h>
using namespace std;
#define ll int
#define inf 0x3f3f3f3f
#define IOS ios::sync_with_stdio(0), cin.tie(0)
const ll N = 1e1 * 1 + 5;
ll n, m, ok;
char a[N][N], b[N][N];
ll dir[][2] = {1, 0, -1, 0, 0, 1, 0, -1};
void dfs(ll x, ll y, ll t) {
    if (ok) return;
    for (int i = 0; i < 4; ++i) {
        ll x2 = x + dir[i][0];
        ll y2 = y + dir[i][1];
        if(x2 < 0 || y2 < 0 || x2 >= n || y2 >= m || b[x2][y2] == 'X') continue;
        if(t > 1 && b[x2][y2] == '#') {
            ok = 1;
            return;
        }
        if(b[x2][y2] != '#') b[x2][y2] = 'X';//保留开头
        dfs(x2, y2, t + 1);
    }
}
void solve() {
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            if (a[i][j] == '.') {
                memcpy(b, a, sizeof b);
                b[i][j] = '#';//标记开头
                ok = 0;
                dfs(i, j, 0);
                if(!ok) {
                    cout << 1 << endl;
                    return;
                }
            }
        }
    }
    cout << 0 << endl;
}

int main( ){
    IOS;
//    ll t; cin >> t;
    ll t = 1;
    while (t--) solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值