DAG

时间:2015-10-23 02:42:59

标签: java graph-theory directed-acyclic-graphs

我目前有一个程序,它将由邻接列表表示的DAG作为系统输入,将其转换为邻接矩阵,然后在邻接矩阵上运行DFS,输出连接组件的数量。

e.g。第一行表示节点的总数,其中以下行表示该节点的每个边。以下图表..

enter image description here

对应于以下输入..

enter image description here

其中输出3是连接组件的数量。

我的问题是以下代码不适用于所有图表,有时会输出比预期更多的组件。任何解释原因的线索都非常有用。

public class conComponents {
private Stack<Integer> stack = new Stack<Integer>();

public static void main(String[] args) {
    int numNodes;
    Scanner sc = null;
    try {
        sc = new Scanner(System.in);
        while (sc.hasNext()) {
            numNodes = sc.nextInt();

            if (numNodes == 0)
                break;

            sc.nextLine();
            int adjMatrix[][] = new int[numNodes][numNodes];

            for (int s = 0; s < numNodes; s++) {
                String[] split = sc.nextLine().split(" ");
                for (int i = 0; i < numNodes; i++) {

                    if (i < split.length) {
                        if (adjMatrix[s][i] != 1) {
                            adjMatrix[s][i] = 0;
                        }

                        if (split[i].equals("")) {
                            adjMatrix[s][i] = 0;

                        } else {
                            adjMatrix[s][Integer.valueOf(split[i])] = 1;
                        }
                    }
                }
            }

            for (int i = 0; i < numNodes; i++) {
                for (int j = 0; j < numNodes; j++) {
                    if (adjMatrix[i][j] == 1 && adjMatrix[j][i] == 0) {
                        adjMatrix[j][i] = 1;
                    }
                }
            }
            conComponents undirectedConnectivity = new conComponents();
            undirectedConnectivity.dfs(adjMatrix);

        }

    } catch (InputMismatchException inputMismatch) {
        System.out.println("Wrong Input format");
    }
    sc.close();
}

public void dfs(int adjMatrix[][]) {
    int numNodes = adjMatrix[0].length;
    int visited[] = new int[numNodes];
    int cc = 0;
    for (int vertex = 0; vertex < numNodes; vertex++) {
        if (visited[vertex] == 0) {
            int element = vertex;
            int i = vertex;
            visited[vertex] = 1;
            cc++;
            stack.push(vertex);
            while (!stack.isEmpty()) {
                element = stack.peek();
                i = element;
                while (i < numNodes) {
                    if (adjMatrix[element][i] == 1 && visited[i] == 0) {
                        stack.push(i);
                        visited[i] = 1;
                        element = i;
                        i = 1;
                        continue;
                    }
                    i++;
                }
                stack.pop();
            }
        }
    }
    System.out.println(cc);
}

}

0 个答案:

没有答案