走迷宫,在有唯一解的情况下
用深度优先搜索进行遍历并找到出口,(从二维矩阵左上节点出发,右下节点为出口,找到一条路径;0表示连通,1表示墙壁),方便自己回忆,立个flag。
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
/**
* 迷宫
* Created by 怪兽 on 2018/2/7.
*/
public class pro2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
int n = scanner.nextInt();
int m = scanner.nextInt();
int array[][] = new int[n][m];
for (int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
array[i][j] = scanner.nextInt();
}
}
core(array);
}
}
/**
* 深度优先搜索
* @param map 地图
*/
private static void core(int map[][]){
int flag[][] = new int[map.length][map[0].length]; //标记是否已被访问过
Stack<Node> stack = new Stack<>(); //辅助栈
int dir[][] = {{1,0},{0,1}}; //能够走得步伐,先竖走,后横走
Node frist = new Node(0,0);
stack.push(frist);
flag[0][0] = 1;
while (!(stack.peek().x == map.length-1 && stack.peek().y == map[0].length - 1)){ //深度优先搜索结束条件,找到出口结束遍历
int x = stack.peek().x;
int y = stack.peek().y;
if(x == map.length - 1) { //到达底部,只能横走
dir[0][0] = x;
dir[0][1] = y + 1;
dir[1][0] = x;
dir[1][1] = y + 1;
}
else if(y == map[0].length - 1){ //到底边缘,只能竖走
dir[0][0] = x+1;
dir[0][1] = y;
dir[1][0] = x + 1;
dir[1][1] = y;
}
else {
dir[0][0] = x + 1;
dir[0][1] = y;
dir[1][0] = x;
dir[1][1] = y + 1;
} //记录接来下能走的步伐
if(flag[dir[0][0]][dir[0][1]] == 0 && map[dir[0][0]][dir[0][1]] == 0) { //没有竖走
Node node = new Node(dir[0][0], dir[0][1]);
stack.push(node);
flag[dir[0][0]][dir[0][1]] = 1;
}
else if (flag[dir[1][0]][dir[1][1]] == 0 && map[dir[1][0]][dir[1][1]] == 0){ //没有横走
Node node = new Node(dir[1][0],dir[1][1]);
stack.push(node);
flag[dir[1][0]][dir[1][1]] = 1;
}
else{ //都走过了
stack.pop();
}
}
Iterator iterator = stack.iterator();
Node node;
while (iterator.hasNext()){
node = (Node)iterator.next();
System.out.println("("+node.x+","+node.y+")");
}
}
}
/**
* 坐标节点,保存坐标位置
*/
class Node{
public int x;
public int y;
public Node(int x,int y){
this.x = x;
this.y = y;
}
}