问题描述
我正在尝试一种算法,该算法将显示带有障碍物(以*表示)的2D数组中2个给定点(起点为S,终点为D)之间的最短路径。到目前为止,我已经实现了BFS来从2个点中查找路径(请参见代码段),但是我很难打印仅最短路径的结果。第一张图片显示了我正在使用的示例输入数组。第二张图片显示了我当前的输出。目标是用“#”替换数组中遍历的元素以绘制点之间的最短路径,但是,如第二张图片所示,它替换了与最短路径相反的所有遍历的元素。另外,它也用#代替了D元素,我不想发生,但是我的主要重点是路径。任何有关如何修改代码的建议将不胜感激,并且我很乐意回答大家可能提出的任何澄清性问题。
boolean [][]visited = new boolean[nrows][ncols];
visited[startX][startY] = true;
Queue<qNode> q = new LinkedList<>();//Source cell marked as visited
qNode s = new qNode(start,0);//Distance of source cell = 0
q.add(s);//Enqueue source cell
//perform BFS starting from source cell
while(!q.isEmpty()) {
qNode cur = q.peek();
Cell pt = cur.cell;
//if we have reached destination cell
if(pt.x == dest.x && pt.y == dest.y) {
System.out.println("Shortest Path Found");
break;
}
//else dequeue front cell and enqueue adjacent cells
q.remove();
for (int i = 0; i < 4; i++) {
int row = pt.x + rowNum[i];
int col = pt.y + colNum[i];
//if cell is valid and unvisited,enqueue it
if(isValid(row,col) && input[row][col] != "*" && !visited[row][col]) {
visited[row][col] = true;
qNode adjCell = new qNode(new Cell(row,col),cur.dist + 1);
q.add(adjCell);
output[row][col] = "#"; //Mark path taken
}
}
}
int z = 0;
for (int o = 0; o < output.length; o++) {
for (int p = 0; p < output[0].length; p++) {
System.out.printf("%5s",output[o][p]);
z++;
if (z == ncols) {
System.out.println("\n");
z = 0;
}
}
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)