| 1 |
/************************************************************************* |
| 2 |
* Copyright (c) 2011 AT&T Intellectual Property |
| 3 |
* All rights reserved. This program and the accompanying materials |
| 4 |
* are made available under the terms of the Eclipse Public License v1.0 |
| 5 |
* which accompanies this distribution, and is available at |
| 6 |
* https://www.eclipse.org/legal/epl-v10.html |
| 7 |
* |
| 8 |
* Contributors: Details at https://graphviz.org |
| 9 |
*************************************************************************/ |
| 10 |
|
| 11 |
/****************************************** |
| 12 |
|
| 13 |
Breadth First Search |
| 14 |
Computes single-source distances for |
| 15 |
unweighted graphs |
| 16 |
|
| 17 |
******************************************/ |
| 18 |
|
| 19 |
#include "config.h" |
| 20 |
|
| 21 |
#include <neatogen/bfs.h> |
| 22 |
#include <util/list.h> |
| 23 |
|
| 24 |
void bfs(int vertex, vtx_data *graph, int n, DistType *dist) { |
| 25 |
DistType closestDist = INT_MAX; |
| 26 |
|
| 27 |
// initial distances with edge weights |
| 28 |
for (int i = 0; i < n; i++) |
| 29 |
dist[i] = -1; |
| 30 |
dist[vertex] = 0; |
| 31 |
|
| 32 |
LIST(int) Q = {0}; |
| 33 |
LIST_PUSH_BACK(&Q, vertex); |
| 34 |
|
| 35 |
while (!LIST_IS_EMPTY(&Q)) { |
| 36 |
const int closestVertex = LIST_POP_FRONT(&Q); |
| 37 |
closestDist = dist[closestVertex]; |
| 38 |
for (size_t i = 1; i < graph[closestVertex].nedges; i++) { |
| 39 |
const int neighbor = graph[closestVertex].edges[i]; |
| 40 |
if (dist[neighbor] < -0.5) { // first time to reach neighbor |
| 41 |
const DistType bump = graph[0].ewgts == NULL |
| 42 |
? 1 |
| 43 |
: (DistType)graph[closestVertex].ewgts[i]; |
| 44 |
dist[neighbor] = closestDist + bump; |
| 45 |
LIST_PUSH_BACK(&Q, neighbor); |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
// for dealing with disconnected graphs |
| 51 |
for (int i = 0; i < n; i++) |
| 52 |
if (dist[i] < -0.5) // `i` is not connected to `vertex` |
| 53 |
dist[i] = closestDist + 10; |
| 54 |
|
| 55 |
LIST_FREE(&Q); |
| 56 |
} |