在 Java 中表示图表

Representing a Graph in Java

我正在开发迷宫系统,但不是图形迷宫系统。我认为迷宫实际上被称为无向图,因为它们不指向彼此。文本文件中的迷宫如下所示:

11 3
2 3
0 3
1 4
5 4
5 7
6 7
7 8
8 9
9 10
0 5

我不知道我用图表表示是否正确。如果你检查我的代码,它似乎是正确的,不是吗?

import java.io.*;
import java.util.Scanner;

class Arc {
    public int nodeNo;
    public Arc next;

    public Arc(int nodeNo, Arc next) {
        this.nodeNo = nodeNo;
        this.next = next;
    }

    public String toString(){
        return "" + nodeNo;
    }
}

class Node {
    int index;
    Arc adjList;

    Node(int index, Arc adjList) {
        this.index = index;
        this.adjList = adjList;
    }

    public String toString() {
        return "" + index;
    }

}

public class Maze {

    Node[] stack;
    private Scanner scan;
    private static Scanner scan2;

    public Maze(String mazeFile) throws FileNotFoundException {
        scan = new Scanner(new File(mazeFile));

        stack = new Node[12];

        for (int n = 0; n < stack.length; n++) {
            stack[n] = new Node(n, null);
        }

        while (scan.hasNext()) {
            int v1 = indexForNode(scan.next());
            int v2 = indexForNode(scan.next());

            stack[v1].adjList = new Arc(v2, stack[v1].adjList);
            stack[v2].adjList = new Arc(v1, stack[v2].adjList);
        }

    }

    int indexForNode(String index) {
        for (int n = 0; n < stack.length; n++) {
            if (stack[n].index == Integer.parseInt(index)) {
                return n;
            }
        }
        return -1;
    }       

    public void print(){
        System.out.println();
        for(int n = 0; n < stack.length; n++){
            System.out.print(stack[n]);
            for(Arc arc = stack[n].adjList; arc != null; arc = arc.next){
                System.out.print(" --> " + stack[arc.nodeNo].index);
            }
            System.out.println("\n");
        }

    }

    public static void main(String[] args) throws FileNotFoundException {
        scan2 = new Scanner(System.in);
        System.out.print("Enter maze file name: ");
        String file = scan2.nextLine();
        Maze maze = new Maze(file);
        maze.print();

    }

}

一般来说,我会说不:这不是一个好方法。一个基本的图,其中边没有权重,被实现为一系列节点有 Many ↔ Many 关系。

所以基本上你的节点看起来像这样:

public class Node {
    private List<Node> out; 
}

有关详细信息,请参阅 this question