定义一个二维数组:
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表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
输入:
一个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
样例输出:
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
解题代码:
01 | //* @author: |
02 | import java.util.*; |
03 | public class Main { |
04 |
05 | private class Point { |
06 |
07 | int x = 0 ; |
08 | int y = 0 ; |
09 |
10 | public Point() { |
11 | this ( 0 , 0 ); |
12 | } |
13 |
14 | public Point( int x, int y) { |
15 | this .x = x; |
16 | this .y = y; |
17 | } |
18 |
19 | public boolean equals(Point p) { |
20 | return (x == p.x) && (y == p.y); |
21 | } |
22 |
23 | @Override |
24 | public String toString() { |
25 | return "(" + x + ", " + y + ")" ; |
26 | } |
27 | } |
28 |
29 | private int [][] maze = null ; //迷宫图 |
30 | private Stack< Point> stack = new Stack< Point>(); |
31 | //保存路径的栈 |
32 |
33 | public Main( int [][] maze) { |
34 | this .maze = maze; |
35 | } |
36 |
37 | public void go() { |
38 | Point out = new Point(maze.length- 1 , maze[ 0 ].length- 1 ); //出口 |
39 | Point in = new Point( 0 , 0 ); //入口 |
40 | Point curNode = in; //当前点为入口 |
41 | Point nextNode = null ; //下一个访问点(目标点) |
42 |
43 | while (!curNode.equals(out)) { |
44 | nextNode = new Point(curNode.x,curNode.y); //设置目标点为当前点,便于下面偏移 |
45 | if ((curNode.x+ 1 )< maze.length&&maze[curNode.x+ 1 ][curNode.y]== 0 ) { //如果下方是空的,则目标点向下偏移 |
46 | nextNode.x++; |
47 | } else if ((curNode.y+ 1 )< maze[ 0 ].length&&maze[curNode.x][curNode.y+ 1 ]== 0 ) { //如果右边是空的,则目标点向右偏移 |
48 | nextNode.y++; |
49 | } else if ((curNode.x- 1 )>= 0 &&maze[curNode.x- 1 ][curNode.y]== 0 ) { //如果上方是空的,则目标点向上偏移 |
50 | nextNode.x--; |
51 | } else if ((curNode.y- 1 )>= 0 &&maze[curNode.x][curNode.y- 1 ]== 0 ) { //如果左边是空的,则目标点向左偏移 |
52 | nextNode.y--; |
53 | } else { //这里是没有路的状态 |
54 | maze[curNode.x][curNode.y] = 3 ; //标记为死路 |
55 | if (stack.isEmpty()) { //判断栈是否为空 |
56 | System.out.println( "Non solution" ); |
57 | return ; |
58 | } |
59 | curNode = stack.pop(); //弹出上一次的点 |
60 | continue ; //继续循环 |
61 | } |
62 |
63 | //如果有路的话会执行到这里 |
64 | stack.push(curNode); //当前点压入栈中 |
65 | maze[curNode.x][curNode.y] = 2 ; //标记为已走 |
66 | curNode = nextNode; //移动当前点 |
67 | } |
68 |
69 | if (nextNode.equals(out)) { |
70 | stack.push(nextNode); //将出口点添加到当前路劲中 |
71 | maze[nextNode.x][nextNode.y] = 2 ; //标记为已走 |
72 | } |
73 | // System.out.println("\n该迷宫的一条可行路劲为:"); |
74 | |
75 |
76 | for ( int i= 0 ;i< stack.size();i++) |
77 | System.out.println(stack.elementAt(i)); |
78 |
79 |
80 | } |
81 |
82 | public static void main(String[] args) { |
83 | Scanner in= new Scanner(System.in); |
84 | int [][] maze= new int [ 5 ][ 5 ]; |
85 | for ( int i= 0 ;i< 5 ;i++) |
86 | for ( int j= 0 ;j< 5 ;j++) |
87 | maze[i][j]=in.nextInt(); |
88 |
89 |
90 | new Main(maze).go(); |
91 | } |
92 | } |