java迷宫路径_java迷宫路径 - 阿豪boy的个人空间 - OSCHINA - 中文开源技术交流社区...

package ahao.alg;

import java.util.List;

import java.util.Stack;

public class SolveMap {

int map[][];

Stack path = new Stack();

List> paths = new Stack>();

public SolveMap(int map[][]) {

this.map = map;

}

public static void main(String[] args) {

int map[][] = { { 1, 1, 1, 1, 1 }, { 1, 0, 0, 0, 1 },

{ 1, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1 } };

SolveMap solveMap = new SolveMap(map);

solveMap.getPath(1, 1, 3, 1);

}

public void getPath(int x, int y, int aimx, int aimy) {

int i, j, dire;

map[x][y] = 1;

path.add(new Node(x, y, -1));

while (!path.isEmpty()) {

i = path.lastElement().x;

j = path.lastElement().y;

dire = path.lastElement().dire;

if (i == aimx && j == aimy) {

paths.add(path);

System.out.println("第" + paths.size() + "条路径为:(需要走"

+ (path.size() - 1) + "步)");

for (int k = 0; k < path.size(); k++) {

System.out.println("\t(" + path.get(k).x + ","

+ path.get(k).y + ")");

}

map[aimx][aimy] = 0;

path.pop();

i = path.lastElement().x;

j = path.lastElement().y;

dire = path.lastElement().dire;

}

int find = 0;

while (dire < 4 && find == 0) {

dire++;

switch (dire) {

case 0:

i = path.lastElement().x - 1;

j = path.lastElement().y;

break;

case 1:

i = path.lastElement().x;

j = path.lastElement().y + 1;

break;

case 2:

i = path.lastElement().x + 1;

j = path.lastElement().y;

break;

case 3:

i = path.lastElement().x;

j = path.lastElement().y - 1;

break;

}

if (map[i][j] == 0) {

find = 1;

}

}

if (find == 1) {

path.lastElement().dire = dire;

path.add(new Node(i, j, -1));

map[i][j] = 1;

} else {

Node node = path.lastElement();

map[node.x][node.y] = 0;

path.pop();

}

}

if (paths.size() == 0)

System.out.println("没有相关路径!");

else {

System.out.println("共有" + paths.size() + "条路径");

}

}

}

class Node {

int x, y, dire;

public Node() {

}

public Node(int x, int y, int dire) {

super();

this.x = x;

this.y = y;

this.dire = dire;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值