【发布时间】:2020-04-17 07:03:03
【问题描述】:
我有一个二维矩阵。 给定一个二维矩阵,其中一些元素用“1”填充,其余元素用“0”填充,除了 2 个元素,其中一个是 S(起点)和 D(终点)。这里的“0”表示您不能遍历到该特定点。您可以从一个单元格向左、向右、向上或向下遍历。给定矩阵中的两个点,找出这些点之间的最短路径。
最短路径之一(从 S 到 D 都互斥)是:[(3, 2), (3, 1), (2, 1), (2, 0)]。如果 S 和 D 之间没有路径,则返回 null。
我编写了一段代码,它返回从 S 到 D 的距离,我的方法返回 int 但如何返回预期的输出? 我的代码:
public class ShortestPath {
public static void main(String args[])
{
char[][] matrix = {
{'S', '0', '1', '1'},
{'1', '1', '0', '1'},
{'0', '1', '1', '1'},
{'1', '0', 'D', '1'}
};
int path = pathExists(matrix);
System.out.println(path);
}
private static int pathExists(char[][] matrix) {
Node source = new Node(0, 0, 0);
Queue<Node> queue = new LinkedList<Node>();
queue.add(source);
while(!queue.isEmpty()) {
Node poped = queue.poll();
if(matrix[poped.x][poped.y] == 'D' ) {
return poped.distanceFromSource;
}
else {
matrix[poped.x][poped.y]='0';
List<Node> neighbourList = addNeighbours(poped, matrix);
queue.addAll(neighbourList);
}
}
return -1;
}
private static List<Node> addNeighbours(Node poped, char[][] matrix) {
List<Node> list = new LinkedList<Node>();
if((poped.x-1 > 0 && poped.x-1 < matrix.length) && matrix[poped.x-1][poped.y] != '0') {
list.add(new Node(poped.x-1, poped.y, poped.distanceFromSource+1));
}
if((poped.x+1 > 0 && poped.x+1 < matrix.length) && matrix[poped.x+1][poped.y] != '0') {
list.add(new Node(poped.x+1, poped.y, poped.distanceFromSource+1));
}
if((poped.y-1 > 0 && poped.y-1 < matrix.length) && matrix[poped.x][poped.y-1] != '0') {
list.add(new Node(poped.x, poped.y-1, poped.distanceFromSource+1));
}
if((poped.y+1 > 0 && poped.y+1 < matrix.length) && matrix[poped.x][poped.y+1] != '0') {
list.add(new Node(poped.x, poped.y+1, poped.distanceFromSource+1));
}
return list;
}
}
class Node {
int x;
int y;
int distanceFromSource;
Node(int x, int y, int dis) {
this.x = x;
this.y = y;
this.distanceFromSource = dis;
}
}
【问题讨论】:
标签: java algorithm shortest-path breadth-first-search