Реализация ширины Первый поиск CLR в JavaJAVA

Программисты JAVA общаются здесь
Anonymous
Реализация ширины Первый поиск CLR в Java

Сообщение Anonymous »

В моем остроумие заканчивается здесь. Я следую за этим Psuedocode от CLR, и я не знаю, почему мой финал для цикла не продолжает давать мне расстояние от данного исходного узла до всех других вершин. Я так потерян, что я не знаю, какую часть этого я испорчу.

Код: Выделить всё

package graph;

import ds.Queue;
import java.util.*;

public class Graph {
public int n;   //number of vertice
public int[][] A;   //the adjacency matrix
private final int WHITE = 2;
private final int GRAY = 3;
private final int BLACK = 4;

public Graph () {
n = 0;
A = null;
}

public Graph (int _n, int[][] _A) {
this.n = _n;
this.A = _A;
}

/*
* Input: s denotes the index of the source node
* Output: the array dist, where dist[i] is the distance between the i-th node to s
*/
public int[] bfs (int s)
{
int [] dist = new int[n];
int [] col = new int[n];
for (int i = 0; i < n; i++)
{
col[i] = WHITE;
dist[i] = Integer.MAX_VALUE;
}
col[s] = GRAY;
dist[s] = 0;

Queue q = new LinkedList();
q.add(s);

while (!q.isEmpty())
{
int u = q.poll();

for (int i : A[u])
{
if(col[i] == WHITE)
{
col[i] = GRAY;
dist[i] = dist[u] + 1;
q.add(i);
}
}
col[u] = BLACK;
}
return dist;

}

public void print_array (int[] array) {
for (int i = 0; i < array.length; i++)
System.out.println(i + ": " + array[i]);
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 8;
int[][] A =
{{0, 1, 0, 0, 1, 0, 0, 0},
{1, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 1},
{1, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 0, 0, 1, 0},
{0, 0, 1, 1, 0, 1, 0, 1},
{0, 0, 0, 1, 0, 0, 1, 0}};
Graph g = new Graph(n, A);
g.print_array(g.bfs(1));
}

}
Псевдо -код

Подробнее здесь: https://stackoverflow.com/questions/795 ... rs-in-java

Вернуться в «JAVA»