[英]how to modify the BFS algorithm to find a path between 2 vertices with a given condition?
I just started to learn graphs and get stuck on this problem. 我刚刚开始学习图形并陷入这个问题。 I'm trying to find the shortest path(minimum number of edges) between two vertices of a graph with the condition that between every 2 intermediary vertices of the path there are 2 alternative paths (doesn't mather the lenght).
我试图找到一个图的两个顶点之间的最短路径(最小边数),条件是该路径的每2个中间顶点之间有2条替代路径(不计算长度)。
This is my BFS algorithm. 这是我的BFS算法。 Colors mean:
颜色表示:
white = didn't reached yet 白色=尚未达到
gray = a reached vertex will stay that color until all his neighbors won't be reached 灰色=到达的顶点将保持该颜色,直到不会到达所有邻居为止
black = reached vertices 黑色=到达顶点
pi[]
contains the parent of the curent vertex pi[]
包含当前顶点的父级
void bfs(int s)
{
int i;
for (i=1; i<=v; i++)
{
if (i != s)
{
color[i] = WHITE;
d[i] = INFTY;
pi[i] = NIL;
}
}
color[s] = GRAY;
d[s] = 0;
pi[s] = NIL;
queueInit(&q);
queuePush(&q,s);
while (!queueEmpty(&q))
{
int u = queueFront(&q);
int j;
for (j=1; j<=adj[u][0]; j++)
{
int x = adj[u][j];
if (color[x] == WHITE)
{
color[x] = GRAY;
d[x] = d[u]+1;
pi[x] = u;
queuePush(&q,x);
}
}
queuePop(&q);
color[u] = BLACK;
}
}
Please help me to change the algorithm to find the shortest path with the given condition or at least give me an advice ! 请帮助我更改算法以找到具有给定条件的最短路径,或者至少给我一个建议!
If you start debugging your code, you'll see one of the problems is that nodes aren't popped before looping on their adjacent nodes , so after all, the algorithm is run again on them, and some of nodes are popped before the algorithm is run on them. 如果您开始调试代码,就会发现问题之一是节点在相邻节点上循环之前没有弹出 ,因此,毕竟算法再次在它们上运行,并且某些节点在算法之前弹出在他们身上跑。
I also don't understand line for (j=1; j<=adj[u][0]; j++)
, which is looping on adjacent vertices. 我也不理解
for (j=1; j<=adj[u][0]; j++)
,该行在相邻顶点上循环。
An implementation of BFS algorithms from cp-algorithms : 来自cp-algorithms的BFS算法的实现 :
vector<vector<int>> adj; // adjacency list representation
int n; // number of nodes
int s; // source vertex
queue<int> q;
vector<bool> used(n);
vector<int> d(n), p(n);
q.push(s);
used[s] = true;
p[s] = -1;
while (!q.empty()) {
int v = q.front();
q.pop(); // The node should be poped before looping on it's adjacent nodes
for (int u : adj[v]) {
if (!used[u]) {
used[u] = true;
q.push(u);
d[u] = d[v] + 1;
p[u] = v;
}
}
}
And then, let's say we want to print the shortest path: 然后,假设我们要打印最短的路径:
if (!used[u]) {
cout << "No path!";
} else {
vector<int> path;
for (int v = u; v != -1; v = p[v])
path.push_back(v);
reverse(path.begin(), path.end());
cout << "Path: ";
for (int v : path)
cout << v << " ";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.