首页 > 代码库 > [JAVA][HDU 1010][Tempter of the Bone]
[JAVA][HDU 1010][Tempter of the Bone]
[java] view plaincopyprint?
- import java.io.BufferedInputStream;
- import java.util.Scanner;
- import com.sun.org.apache.regexp.internal.recompile;
- public class Main {
- static int row;
- static int col;
- static int step;
- static char maze[][] = new char[20][20];// save the maze
- static boolean isPosWalked[][] = new boolean[20][20];// check if the pos have been walked
- static boolean isSuccess;
- public static boolean dfs(char maze[][], int y, int x, int currentStep) {
- if (maze[y][x] == ‘D‘ && currentStep == step) {
- isSuccess = true;
- } else if (maze[y][x] == ‘D‘ && currentStep != step) {
- return false;// if we got destination but not the requested step,go back to the upper
- }
- isPosWalked[y][x] = true;
- // go right
- if (x < col - 1 && maze[y][x + 1] != ‘X‘ && !isPosWalked[y][x + 1]) {// if we can walk to the right side
- dfs(maze, y, x + 1, currentStep + 1);
- }
- // go down
- if (y < row - 1 && maze[y + 1][x] != ‘X‘ && !isPosWalked[y + 1][x]) {// if we can walk to the right side
- dfs(maze, y + 1, x, currentStep + 1);
- }
- // go left
- if (x > 0 && maze[y][x - 1] != ‘X‘ && !isPosWalked[y][x - 1]) {// if we can walk to the right side
- dfs(maze, y, x - 1, currentStep + 1);
- }
- // go up
- if (y > 0 && maze[y - 1][x] != ‘X‘ && !isPosWalked[y - 1][x]) {// if we can walk to the right side
- dfs(maze, y - 1, x, currentStep + 1);
- }
- isPosWalked[y][x] = false;
- return false;
- }
- public static void print(char maze[][], int y, int x) {
- for (int i = 0; i < y; i++) {
- for (int j = 0; j < x; j++) {
- System.out.print(maze[i][j]);
- }
- System.out.println();
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(new BufferedInputStream(System.in));
- row = sc.nextInt();
- col = sc.nextInt();
- step = sc.nextInt();
- int startY = 0, startX = 0;
- while (row != 0 || col != 0 || step != 0) {
- for (int i = 0; i < row; i++) {
- String tmp = sc.next();
- for (int j = 0; j < col; j++) {
- maze[i][j] = tmp.charAt(j);// trans str to char
- if (maze[i][j] == ‘S‘) {
- startY = i;
- startX = j;
- }
- }
- }
- isSuccess = false;
- for (int i = 0; i < 20; i++) {
- for (int j = 0; j < 20; j++) {
- isPosWalked[i][j] = false;
- }
- }
- dfs(maze, startY, startX, 0);
- if (isSuccess) {
- System.out.println("YES");
- } else {
- System.out.println("NO");
- }
- // print(maze, y, x);
- row = sc.nextInt();
- col = sc.nextInt();
- step = sc.nextInt();
- }
- }
- }
最近写的题目多用到dfs,一年前用C没写出来一直WA,今天看到hdu的Discussion有同学提供了很多测试数据,逐个把答案不同的调试一下终于AC
有这么几个要点:
1.
2 2 3
SD
..
这样的testcase也是要输出YES的,转了一个圈什么的,所以首次到达Destination也要判断一下是否和Required-Step完全符合
2.其实也是比较基础的,返回到upper recrusion的时候要注意将各种值回归进入时的状态
[JAVA][HDU 1010][Tempter of the Bone]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。