[英]Does Dijkstra algorithm keep track of visited nodes to find the shortest path?
[英]graph to find shortest path to origin using nodes I visited
給定方向和路線,我想知道最后只使用我以前去過的地方回到我開始的地方(原點)的最短路徑
(下圖示例,N 為北,S 為南等)
示例輸入:NNEEEENWNENNSEEEWWWSWSESWWWNNNNWWWSSNNNNEE
樣品 Output:14
我在 java 工作,想使用廣度優先搜索算法並想使用圖表,這是我可以構建這個圖表並查看這個問題的最佳方式?
有人可以幫忙嗎?
您可以通過讀取輸入生成已訪問單元格的圖表,然后從最后一個 position 在此圖表上運行 BFS。
要生成圖表,您可以執行以下操作:
for each direction :
create node for the cell if not already existing
for each adjacent cell, if visited then connect them together
只需運行一個 BFS,從末端開始並到達您已經通過的位置,一旦到達原點 position 就停止:
#include <bits/stdc++.h>
using namespace std;
int m[9][10];
int v[9][10];
struct point{
int x, y, dist;
point(){}
point(int x, int y){this->x = x; this->y = y; dist = 0;}
point(int x, int y, int dist){this->x = x; this->y = y; this->dist = dist;}
bool operator == (const point &rhs) const { return rhs.x == x && rhs.y == y; }
};
point origin(2, 8);
point target(2, 0);
int BFS(){
queue<point> q;
q.push(target);
while(!q.empty()){
point p = q.front();
q.pop();
v[p.y][p.x] = 1;
if(p == origin) return p.dist;
if(p.x > 0 && !v[p.y][p.x - 1] && m[p.y][p.x - 1]) q.push(point(p.x - 1, p.y, p.dist + 1)); //left
if(p.x < 9 && !v[p.y][p.x + 1] && m[p.y][p.x + 1]) q.push(point(p.x + 1, p.y, p.dist + 1)); //right
if(p.y > 0 && !v[p.y - 1][p.x] && m[p.y - 1][p.x]) q.push(point(p.x, p.y - 1, p.dist + 1)); //up
if(p.y < 8 && !v[p.y + 1][p.x] && m[p.y + 1][p.x]) q.push(point(p.x, p.y + 1, p.dist + 1)); //down
}
return -1;
}
int main(){
memset(m, 0, sizeof(m));
memset(v, 0, sizeof(v));
m[origin.y][origin.x] = 1;
string path = "NNEEEENWNENNSEEEWWWSWSESWWWNNNNWWWSSNNNNEE";
point o(origin.x, origin.y);
for(int i = 0; i < path.size(); i++){
if(path[i] == 'N') o.y--;
else if(path[i] == 'S') o.y++;
else if(path[i] == 'W') o.x--;
else if(path[i] == 'E') o.x++;
m[o.y][o.x] = 1;
}
cout<<"dist = "<<BFS()<<endl;
}
OUTPUT:距離 = 14 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.