poj 3984 迷宫问题(dfs)

迷宫问题
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14417   Accepted: 8611

Description

定义一个二维数组: 

int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。

Input

一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。

Output

左上角到右下角的最短路径,格式如样例所示。

Sample Input

0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

Sample Output

(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

Java AC 代码

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    
    static List<Point> path = new ArrayList<Point>(); //记录当前路径
    
    static List<Point> result;  //记录结果路径
    
    static int steps = 24;  //步数
    
    static int maze[][] = new int[5][5]; //输入的迷宫布局
    
    static int dx[] = {-1, 0, 0, 1}; //四个方向的x,y变化
    static int dy[] = {0, 1, -1, 0};
    
    static boolean marked[][] = new boolean[5][5]; //标记位
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        for(int i = 0; i < 5; i++) 
            for(int j = 0; j < 5; j++) {
                maze[i][j] = sc.nextInt();
            }
        path.add(new Point(0, 0));
        dfs(0, 0, 0);
        for(int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i));
        }
        
    }
    
    public static void dfs(int row, int col, int curSteps) {
        if(row == 4 && col == 4) //到了出口,判断是否步数小于当前结果的最小步数,如果小于,则把结果列表更新
            if(curSteps < steps) {
                steps = curSteps;
                result = new ArrayList<Point>(path);
                return;
            }
        for(int i = 0; i < 4; i++) {
            int _row = row + dy[i];
            int _col = col + dx[i];
            if(_row >= 0 && _row <= 4 && _col >=0 && _col <=4 && !marked[_row][_col] && maze[_row][_col] == 0) {
                marked[_row][_col] = true;
                path.add(new Point(_row, _col));
                dfs(_row, _col, curSteps + 1);
                path.remove(path.size() - 1);
                marked[_row][_col] = false;
            }    
        }        
    }
    
}

class Point{
    
    int row;
    int column;
    public Point(int row, int column) {
        this.row = row;
        this.column = column;
    }
    @Override
    public String toString() {
        return "(" + row + ", " + column + ")";
    }
    
}
原文地址:https://www.cnblogs.com/kkkkkk/p/5536824.html