我正在开发一个迷宫系统,但不是图形迷宫系统。我认为迷宫实际上被称为无向图,因为它们不直接指向彼此。迷宫在文本文件中看起来像这样:
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了解更多信息。
关于java - 用 Java 表示图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884203/