最短路径Java 2d数组
我正在制作一个2d数组作为包含节点的游戏地图的游戏。长度和宽度不一样。这些节点具有字段类型,需要达到不同的移动量。A需要一个,B需要两个,C联系不到。当我访问一个节点时,我将visted属性设置为true,但是如果没有其他路径可用,则应该使用visted节点。我想将移动值存储在队列中,以便在下一轮中轮询它。如何找到从源到目标的最短路径并重用访问的节点?我已经阅读了一些指南,关于为网格中的最后一个元素寻找最短路径,但是我的目标可以是任何地方 到目前为止,我的代码是:最短路径Java 2d数组,java,arrays,depth-first-search,breadth-first-search,shortest-path,Java,Arrays,Depth First Search,Breadth First Search,Shortest Path,我正在制作一个2d数组作为包含节点的游戏地图的游戏。长度和宽度不一样。这些节点具有字段类型,需要达到不同的移动量。A需要一个,B需要两个,C联系不到。当我访问一个节点时,我将visted属性设置为true,但是如果没有其他路径可用,则应该使用visted节点。我想将移动值存储在队列中,以便在下一轮中轮询它。如何找到从源到目标的最短路径并重用访问的节点?我已经阅读了一些指南,关于为网格中的最后一个元素寻找最短路径,但是我的目标可以是任何地方 到目前为止,我的代码是: public class No
public class Node {
int x;
int y;
FieldType type;
boolean visited;
}
public enum FieldType {
A,B,C
}
public enum Move {
UP,
DOWN,
LEFT,
RIGHT
}
public class Test {
Queue<Move> queue;
Node[][] grid;
public Test(int l, int w, Node src, Node target) {
queue = new LinkedList<>();
grid = createGrid(l, w);
}
public Move getNextMove(Node src, Node target) {
if(queue.isEmpty()) {
findPath(src, target);
}
return queue.poll();
}
public void findPath(Node src, Node target) {
int x = src.x;
int y = src.y;
Node next = null;
Move nextMove = null;
if(next == null && isValid(x, y-1)) {
next = grid[x][y-1];
nextMove = Move.UP;
}
if(next == null && isValid(x, y+1)) {
next = grid[x][y + 1];
nextMove = Move.DOWN;
}
if(next == null && isValid(x + 1, y)) {
next = grid[x + 1][y];
nextMove = Move.RIGHT;
}
if(next == null && isValid(x - 1, y)) {
next = grid[x - 1][y];
nextMove = Move.LEFT;
}
next.visited = true;
int dist = getDistance(next.type);
for(int i = 0; i < dist; i++) {
queue.add(nextMove);
}
}
public int getDistance(FieldType type) {
int dist = 0;
switch(type) {
case A:
dist = 1;
break;
case B:
dist = 2;
break;
case C:
dist = Integer.MAX_VALUE;
break;
default:
break;
}
return dist;
}
public boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && y < grid.length
&& x < grid[0].length && grid[x][y].visited == false
&& grid[x][y].type != FieldType.C;
}
public Node[][] createGrid(int l, int w) {
return new Node[w][l];
}
}
公共类节点{
int x;
int-y;
字段类型;
参观;
}
公共枚举字段类型{
A、 B,C
}
公共枚举移动{
向上的
下来,,
左边
正确的
}
公开课考试{
排队;
节点[][]网格;
公共测试(int l、int w、节点src、节点目标){
队列=新的LinkedList();
网格=创建网格(l,w);
}
公共移动getNextMove(节点src,节点目标){
if(queue.isEmpty()){
findPath(src,target);
}
返回queue.poll();
}
公共void findPath(节点src,节点目标){
int x=src.x;
int y=src.y;
Node next=null;
Move nextMove=null;
if(next==null&&isValid(x,y-1)){
下一步=网格[x][y-1];
nextMove=Move.UP;
}
if(next==null&&isValid(x,y+1)){
下一步=网格[x][y+1];
nextMove=Move.DOWN;
}
if(next==null&&isValid(x+1,y)){
下一步=网格[x+1][y];
nextMove=Move.RIGHT;
}
if(next==null&&isValid(x-1,y)){
下一步=网格[x-1][y];
nextMove=Move.LEFT;
}
next.visted=true;
int dist=getDistance(next.type);
对于(int i=0;i=0&&y>=0&&y