递归问题:一穿越迷宫

迷宫问题的解决涉及到大量的试探和失败:选择一条路径,在无法前景时折回,并选择其他还未尝试过的路径。使用递归能够很好的处理这类问题。


package com.chingcloud.test01;


public class Maze {
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)){
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 ;
}
public 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 ;
}
public static void main(String[] args) {
Maze labyrinth = new Maze() ;
System.out.println(labyrinth);
if(labyrinth.traverse(0,0)){
System.out.println("The maze was successfully traversed!");
}else{
System.out.println("There is no possible path.");
}
System.out.println(labyrinth);
}
}


result



1110110001111
1011101111001
0000101010100
1110111010111
1010000111001
1011111101111
1000000000000
1111111111111


The maze was successfully traversed!


7770110001111
3077707771001
0000707070300
7770777070333
7070000773003
7077777703333
7000000000000
7777777777777

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值