package com.kingdz.algorithm.time201705;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import com.kingdz.algorithm.time201703.Algo29;
/**
* 迷宫求解,广度优先遍历
*
* @author kingdz
*
*/
public class Algo27 {
public static void main(String[] args) {
int[][] maze = Algo29.genMaze(7, 40);
Algo29.printMaze(maze);
System.out.println("-----------------------------------------");
if (solveMaze(maze, new MazePoint(0, 0), new MazePoint(6, 35))) {
Algo29.printMaze(maze);
System.out.println("-----------------------------------------");
}
}
private static boolean solveMaze(int[][] maze, MazePoint start, MazePoint end) {
Map<MazePoint, MazePoint> map = new HashMap<MazePoint, MazePoint>();
int[][] next = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
Queue<Node> queue = new ArrayDeque<Node>();
queue.add(new Node(start.getX(), start.getY(), 1));
maze[start.getX()][start.getY()] = 3;
map.put(new MazePoint(start.getX(), start.getY()), new MazePoint(-1, -1));
while (!queue.isEmpty()) {
Node old = queue.poll();
for (int i = 0; i < 4; i++) {
Node newNode = new Node(old.x + next[i][0], old.y + next[i][1], old.step + 1);
if (newNode.x < 0 || newNode.y < 0 || newNode.x >= maze.length || newNode.y >= maze[0].length) {
continue;
}
if (newNode.x == end.getX() && newNode.y == end.getY()) {
System.out.println(newNode.step);
map.put(new MazePoint(newNode.x, newNode.y), new MazePoint(old.x, old.y));
int x = newNode.x;
int y = newNode.y;
while (x != -1 && y != -1) {
maze[x][y] = 2;
MazePoint mz = map.get(new MazePoint(x, y));
x = mz.getX();
y = mz.getY();
}
return true;
}
if (maze[newNode.x][newNode.y] == 0) {
map.put(new MazePoint(newNode.x, newNode.y), new MazePoint(old.x, old.y));
queue.add(newNode);
maze[newNode.x][newNode.y] = 3;
}
}
}
return false;
}
private static class Node {
private int prex;
private int prey;
private int x;
private int y;
private int step;
public Node(int x, int y, int step) {
super();
this.x = x;
this.y = y;
this.step = step;
}
@Override
public String toString() {
return "Node [prex=" + prex + ", prey=" + prey + ", step=" + step + ", x=" + x + ", y=" + y + "]";
}
}
}
class MazePoint {
private int x;
private int y;
public MazePoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof MazePoint) {
MazePoint p2 = (MazePoint) obj;
if (this.x == p2.getX() && this.y == p2.getY()) {
return true;
}
}
return super.equals(obj);
}
@Override
public int hashCode() {
String str = "" + this.x + "," + this.y;
return str.hashCode();
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
【算法】程序猿不写代码是不对的63
最新推荐文章于 2023-03-11 12:53:26 发布