迷宫问题-(Java源码)

由于之前 参加了不少校园招聘的笔试, 碰到了些问题,回来做了些总结!

迷宫问题,  肯定会用到回溯,在本题具体是指,当某个位置的四个方向都走不通(除了,走到这个位置的那个方向)时,

则返回此位置 之前的那个位置,再从其他方向走(其实,就是要用到 ‘栈’)。代码和结果如下(虽然不够简洁,但是思路还算清晰吧,注意防止在走不通的情况下产生回路!):


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=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 acrossMiGong(){	
	  
	  Stack s = new Stack();
	  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 s = am.acrossMiGong();		
		
		System.out.println(s);
		return;
	}	
}


..迷宫问题-(Java源码)_第1张图片

你可能感兴趣的:(Java,算法)