java程序走矩阵迷宫


import java.util.Arrays;
import java.util.Stack;

/**
* 迷宫
*
* @author 风华褚胜
*/
public class MiGong {

public static void main(String[] args) {
Stack<Position> stack = new Stack<Position>(); // 保存迷宫路径
Stack<Object[]> end = new Stack<Object[]>();// 保存可通路路径
new MiGong().f(getMiGong(), 1, 1/* 是起始坐标 */, 8, 8/* 是终点坐标 */,
0/* 上一步的方向 */, stack, end);

int shor = Integer.MAX_VALUE;
int index = 0;
for (int i = 0; i < end.size(); i++) {
if (shor > end.get(i).length) {
index = i;
shor = end.get(i).length;
}
}

if (end.size() != 0) {
System.out.println("最短路径:");
System.out.println(Arrays.toString(end.get(index)));
} else
System.out.println("无通路");
}

public static int[][] getMiGong() {
// int[][] num = { { 1, 1, 1, 1, 1 },
// { 1, 0, 1, 1, 1 },
// { 1, 0, 1, 1, 1 },
// { 1, 0, 0, 0, 1 },
// { 1, 1, 0, 0, 1 },
// { 1, 1, 1, 1, 1 } };
int[][] num = { { 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 0, 1, 1, 0, 1 },
{ 1, 0, 1, 0, 0, 1, 0, 0, 1 }, { 1, 0, 1, 0, 1, 0, 1, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 1, 0, 1 }, { 1, 1, 0, 1, 1, 0, 1, 1, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
return num;
}

/**
* 求取所有路径
*
* @param num
* 迷宫矩阵
* @param start_row
* 开始坐标x
* @param start_col
* 开始坐标y
* @param end_row
* 结束坐标x
* @param end_col
* 结束坐标y
* @param dro
* 上一步走的方向
* @param s
* 保存迷宫路径
* @param end
* 保存可通路路径
*/
public void f(int[][] num, int start_row, int start_col, int end_row,
int end_col, int dro, Stack<Position> s, Stack<Object[]> end) {
// System.out.println(Arrays.toString(s.toArray()));

s.push(new Position(start_row, start_col));
if (start_row == end_row && start_col == end_col) {
System.out.println(Arrays.toString(s.toArray()));
end.push(s.toArray());
s.pop();
return;
}
num[start_row][start_col] = 1;
if (dro != 2 && num[start_row - 1][start_col] == 0) {
f(num, start_row - 1, start_col, end_row, end_col, 1, s, end);
}
if (dro != 1 && num[start_row + 1][start_col] == 0) {
f(num, start_row + 1, start_col, end_row, end_col, 2, s, end);
}
if (dro != 4 && num[start_row][start_col - 1] == 0) {
f(num, start_row, start_col - 1, end_row, end_col, 3, s, end);
}
if (dro != 3 && num[start_row][start_col + 1] == 0) {
f(num, start_row, start_col + 1, end_row, end_col, 4, s, end);
}
num[start_row][start_col] = 0;
s.pop();
return;
}

/**
* 坐标点的表示类
*
* @author 风华褚胜
*/
class Position {
public int row;
public int col;

public Position(int row, int col) {
this.row = row;
this.col = col;
}

@Override
public String toString() {
return "(" + row + "," + col + ")";
}
}
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值