由于之前 参加了不少校园招聘的笔试, 碰到了些问题,回来做了些总结!
迷宫问题, 肯定会用到回溯,在本题具体是指,当某个位置的四个方向都走不通(除了,走到这个位置的那个方向)时,
则返回此位置 之前的那个位置,再从其他方向走(其实,就是要用到 ‘栈’)。代码和结果如下(虽然不够简洁,但是思路还算清晰吧,注意防止在走不通的情况下产生回路!):
import java.util.Stack;
//迷宫矩阵
final class Matrix{
static int[][] matrix =
{
{0,0,1,1,0},
{0,0,0,1,0},
{1,1,0,1,1},
{1,0,0,1,1},
{1,0,1,0,0},
{1,0,0,0,0}
};
static final int row = matrix.length; //行
static final int col = matrix[0].length; //列
}
class Node{
int x, y;
boolean left = false, right = false, up = false, down = false;
Node(int x, int y){
this.x = x;
this.y = y;
}
boolean isRight(){
if(y<Matrix.col -1)
{
return (Matrix.matrix[x][y+1] == 0);
}
right = true;
return false;
}
boolean isLeft(){
if(y>=1)
{
return (Matrix.matrix[x][y-1]==0);
}
left = true;
return false;
}
boolean isUp(){
if(x>=1)
{
return (Matrix.matrix[x-1][y] == 0);
}
up = true;
return false;
}
boolean isDown(){
if(x<Matrix.row-1)
{
return (Matrix.matrix[x+1][y]==0);
}
down = true;
return false;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
return (x==other.x && y==other.y);
}
public String toString(){
return "["+x+","+y+"]";
}
}
class AcrossMiGong{
boolean isSucceed(Node node){
if((node.x == Matrix.row-1) && (node.y == Matrix.col-1))
return true;
return false;
}
//-寻路
Stack<Node> acrossMiGong(){
Stack<Node> s = new Stack<Node>();
Node start = new Node(0,0);
s.add(start);
int k = 0;
// 右-->下--左-->上
while(!s.empty())
{
if(!start.right && start.isRight())
{
Node nright = new Node(start.x, start.y+1);
if(!s.contains(nright)) //防止在走不通的情况下, 产生环路现象! 下同
{
nright.left = true;
start.right = true;
s.add(nright);
start = nright;
}else
{
start.right = true;
}
}else if(!start.down && start.isDown())
{
Node ndown = new Node(start.x+1, start.y);
if(!s.contains(ndown))
{
start.down = true;
ndown.up = true;
s.add(ndown);
start = ndown;
}else
{
start.down = true;
}
}else if(!start.left && start.isLeft())
{
Node nleft = new Node(start.x, start.y-1);
if(!s.contains(nleft))
{
start.left = true;
nleft.right = true;
s.add(nleft);
start = nleft;
}else
{
start.left = true;
}
}else if(!start.up && start.isUp())
{
Node nup = new Node(start.x-1, start.y);
if(!s.contains(nup))
{
start.up = true;
nup.down = true;
s.add(nup);
start = nup;
}else
{
start.up = true;
}
}else if(!s.empty())
{
// System.out.println(s);
// System.out.println();
s.pop();
if(s.empty())
{
System.out.println("cannot arrive aim!");
return null;
}
start = s.peek();
}
if(isSucceed(start))
{
return s;
}
}
return null;
}
}
public class MiGongTest{
public static void main(String[] args){
System.out.println("-----------------MiGongTest-----------------");
AcrossMiGong am = new AcrossMiGong();
Stack<Node> s = am.acrossMiGong();
System.out.println(s);
return;
}
}
..