
一、思路分析
1.先创建一个二维数组模拟迷宫,把相应点置为1
2.规则:0表示该点没有走过;1表示墙;2表示通路可以走;3表示该点已经走过,但走不通
3.策略:下->右->上->左
二、代码实现
public class MG {
public static void main(String[] args) {
//0:表示没走过;1:表示墙;2:表示可以走通;3:表示走过但不通;策略:上右下左
int[][] map = new int[8][7];
for (int i = 0; i < 7; i++) {
map[0][i] = 1;
map[7][i] = 1;
}
for (int i = 0; i < 8; i++) {
map[i][0] = 1;
map[i][6] = 1;
}
map[3][1] = 1;
map[3][2] = 1;
list(map);
setWay4(map,1,1);
list(map);
}
//实现方法:利用递归回溯来解决小球路线问题
//1.上右下左
public static boolean setWay1(int[][] map,int i,int j){
//先判定是否到了终点
if(map[6][5] == 2){
return true;
}
if(map[i][j] == 0){
map[i][j] = 2;
if(setWay1(map,i-1,j)){
return true;
}else if(setWay1(map,i,j+1)){
return true;
}else if(setWay1(map,i+1,j)){
return true;
}else if(setWay1(map,i,j-1)){
return true;
}else {
map[i][j] = 3;
return false;
}
}else {
return false;
}
}
//2.右下左上
public static boolean setWay2(int[][] map,int i,int j){
//先判定是否到了终点
if(map[6][5] == 2){
return true;
}
if(map[i][j] == 0){
map[i][j] = 2;
if(setWay2(map,i,j+1)){
return true;
}else if(setWay2(map,i+1,j)){
return true;
}else if(setWay2(map,i,j-1)){
return true;
}else if(setWay2(map,i-1,j)){
return true;
}else {
map[i][j] = 3;
return false;
}
}else {
return false;
}
}
//3.下左上右
public static boolean setWay3(int[][] map,int i,int j){
//先判定是否到了终点
if(map[6][5] == 2){
return true;
}
if(map[i][j] == 0){
map[i][j] = 2;
if(setWay3(map,i+1,j)){
return true;
}else if(setWay3(map,i,j-1)){
return true;
}else if(setWay3(map,i-1,j)){
return true;
}else if(setWay3(map,i,j+1)){
return true;
}else {
map[i][j] = 3;
return false;
}
}else {
return false;
}
}
//4.左上右下
public static boolean setWay4(int[][] map,int i,int j){
//先判定是否到了终点
if(map[6][5] == 2){
return true;
}
if(map[i][j] == 0){
map[i][j] = 2;
if(setWay4(map,i,j-1)){
return true;
}else if(setWay4(map,i-1,j)){
return true;
}else if(setWay4(map,i,j+1)){
return true;
}else if(setWay4(map,i+1,j)){
return true;
}else {
map[i][j] = 3;
return false;
}
}else {
return false;
}
}
//遍历地图
public static void list(int[][] map){
System.out.println("目前地图的情况:");
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 7; j++) {
System.out.print(map[i][j] + "\t");
}
System.out.println();
}
}
}
1万+



被折叠的 条评论
为什么被折叠?



