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;
}