码迷,mamicode.com
首页 > 编程语言 > 详细

Java --- 走迷宫

时间:2016-09-28 16:23:00      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

走迷宫需要考虑大量的实验和错误:沿着一条路径走,当不能再向前走时回溯,然后尝试另一条以前没尝试过的选择。可是使用递归算法。

//**********************************************************
// MaseSearch.java
//**********************************************************
public class MaseSearch 
{
	public static void main(String[] args)
	{
		Mase labyrinth = new Mase();
		
		System.out.println(labyrinth);
		
		if(labyrinth.traverse(0,0))
			System.out.println("The Mase was successfully traversed!");
		else
			System.out.println("There is no possble path");
		
		System.out.println(labyrinth);
	}
}

//**********************************************************
// Mase.java
//**********************************************************
public class Mase {
	private final int TRIED = 3;
	private final int PATH = 7;
	
	private int[][] grid={{1,1,1,0,1,1,0,0,0,1,1,1,1},
			              {1,0,1,1,1,0,1,1,1,1,0,0,1},
			              {0,0,0,0,1,0,1,0,1,0,1,0,0},
			              {1,1,1,0,1,1,1,0,1,0,1,1,1},
			              {1,0,1,0,0,0,0,1,1,1,0,0,1},
			              {1,0,1,1,1,1,1,1,0,1,1,1,1},
			              {1,0,0,0,0,0,0,0,0,0,0,0,0},
			              {1,1,1,1,1,1,1,1,1,1,1,1,1}};
	
	public boolean traverse(int row,int column)
	{
		boolean done = false;
		
		if(valid(row,column))  // 判断是否为1 ,为1 则真
		{
			grid[row][column] = TRIED;
			
			if(row == grid.length-1 && column == grid[0].length-1)
				done = true;
			else
			{
				done = traverse(row+1,column);
				if(!done)
					done = traverse(row,column+1);
				if(!done)
					done = traverse(row-1,column);
				if(!done)
					done = traverse(row,column-1);
			}
			if(done)
				grid[row][column]=PATH;
		}
		return done;
	}
	
	private boolean valid(int row,int column)
	{
		boolean result = false;
		if(row>=0 && row<grid.length && column >= 0 && column < grid[row].length)
			if(grid[row][column] == 1)
				result = true;
		
		return result;
	}
	
	public String toString()
	{
		String result = "\n";
		for(int row = 0;row < grid.length;row++)
		{
			for(int column=0; column<grid[row].length;column++)
				result += grid[row][column] + " ";
				result += "\n";
		}
		return result;
	}
}

 

  

 

 

  

 

 

  

 

Java --- 走迷宫

标签:

原文地址:http://www.cnblogs.com/liuxinlei/p/5916306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!