[英]graph to find shortest path to origin using nodes I visited
Given the directions and a route, I want to know the shortest path to, in the end, get back to where I started(origin) only using places I have visited before给定方向和路线,我想知道最后只使用我以前去过的地方回到我开始的地方(原点)的最短路径
(example of the image below, N is north, S south etc) (下图示例,N 为北,S 为南等)
Sample Input: NNEEEENWNENNSEEEWWWSWSESWWWNNNNWWWSSNNNNEE示例输入:NNEEEENWNENNSEEEWWWSWSESWWWNNNNWWWSSNNNNEE
Sample Output: 14样品 Output:14
image with example, red is shortest path and gives the 14 output带有示例的图像,红色是最短路径,并给出 14 output
I am working in java and want to use a Breadth-First Search algorithm and want to use a graph, which is the best way I can construct this graph and look a this problem?我在 java 工作,想使用广度优先搜索算法并想使用图表,这是我可以构建这个图表并查看这个问题的最佳方式?
Can someone help?有人可以帮忙吗?
You can generate a graph of visited cells by reading the input and then run a BFS on this graph from the last position.您可以通过读取输入生成已访问单元格的图表,然后从最后一个 position 在此图表上运行 BFS。
To generate the graph you can do:要生成图表,您可以执行以下操作:
for each direction :
create node for the cell if not already existing
for each adjacent cell, if visited then connect them together
Just run a BFS, starting from the end and going to positions you have already passed, stopping once you reach the origin position:只需运行一个 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: dist = 14 . OUTPUT:距离 = 14 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.