🍑 OJ专栏
🍑 HDOJ 1010 Tempter of the bone
输入
4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0
输出
NO
YES
🙈 本想着 BFS 找到最短时间,只要最短时间 < T 理论上是可以的……奈何要考虑的情况过多……
🍑 思路
🍤 DFS搜出到达终点的所有时间,判断时间是否符合条件
🍤 剪枝:奇偶剪枝(起点与终点的曼哈顿距离的 奇偶性 与 要走的步数 相同
🍑 AC
import java.util.*;
public class N1010骨头的诱惑
{
static int N = 10, n, m, T;
static char[][] g = new char[N][N];
static boolean[][] st = new boolean[N][N];
static int[] dx = { 1, 0, -1, 0 };
static int[] dy = { 0, 1, 0, -1 };
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
n = sc.nextInt();
m = sc.nextInt();
T = sc.nextInt();
if (n == 0 && m == 0 && T == 0)
break;
// x,y 记录终点坐标
int x = 0;
int y = 0;
// xx,yy 记录终点坐标
int xx = 0;
int yy = 0;
for (int i = 0; i < n; i++)
{
char[] arr = sc.next().toCharArray();
for (int j = 0; j < m; j++)
{
g[i][j] = arr[j];
if (g[i][j] == 'S')
{
x = i;
y = j;
}
if (g[i][j] == 'D')
{
xx = i;
yy = j;
}
}
}
for (int i = 0; i < N; i++)
Arrays.fill(st[i], false);
st[x][y] = true;
// 逻辑运算符的断路效果,判断距离是否有解,必须放在前边才可以实现剪枝效果
if (dis(x, y, xx, yy, T) && dfs(x, y, 0))
System.out.println("YES");
else
{
System.out.println("NO");
}
}
}
//传说中的奇偶剪枝
private static boolean dis(int x, int y, int xx, int yy, int t)
{
int tt = Math.abs(xx - x) + Math.abs(yy - y);//起点和终点的曼哈顿距离
if (Math.abs(tt - t) % 2 == 0)// 曼哈顿距离 与 目标时间t 的奇偶性要相同才是有解距离
return true;
return false;
}
private static boolean dfs(int x, int y, int t)
{
if (t > T)
return false;
if (g[x][y] == 'D' && t == T)
return true;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || xx >= n || yy < 0 || yy >= m || st[xx][yy] || g[xx][yy] == 'X')
continue;
st[xx][yy] = true;
if (dfs(xx, yy, t + 1))
return true;
st[xx][yy] = false;
}
return false;
}
}