Java 无向图的邻接表
有人知道我在哪里可以获得使用邻接列表表示无向图的通用示例代码吗 图形数据来自.txt文件:节点在第一行指定,用空格分隔。边在以下行中指定,每条边在单独的行中 像这样Java 无向图的邻接表,java,graph,adjacency-list,Java,Graph,Adjacency List,有人知道我在哪里可以获得使用邻接列表表示无向图的通用示例代码吗 图形数据来自.txt文件:节点在第一行指定,用空格分隔。边在以下行中指定,每条边在单独的行中 像这样 1 2 3 4 5 6 7 8 9 1 2 1 4 1 3 2 4 2 5 3 6 4 6 5 7 5 8 6 9 7 9 8 9 我的.txt文件未与graph方法连接。我还得到以下NPE错误: Error: java.lang.NullPointerException 创建邻接列表&对无向图执行标准图
1 2 3 4 5 6 7 8 9
1 2
1 4
1 3
2 4
2 5
3 6
4 6
5 7
5 8
6 9
7 9
8 9
我的.txt文件未与graph方法连接。我还得到以下NPE错误:
Error: java.lang.NullPointerException
创建邻接列表&对无向图执行标准图ADT方法
//TON of imports up here (removed for now)
class Graph<V> implements GraphADT1 <V>{
// Map of adjacency lists for each node
private HashMap<Integer, LinkedList<Integer>> adj;
private ArrayList<V> vertices;
private HashMap<V, LinkedHashSet<V>> neighbors;
private HashMap<V, Set<V>> neighborsView;
private int edgeCount;
public Graph(int[] nodes) {
vertices = new ArrayList<V>();
neighbors = new HashMap<V, LinkedHashSet<V>>();
neighborsView = new HashMap<V, Set<V>>();
adj = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < nodes.length; ++i) {
adj.put(i, new LinkedList<Integer>());
}
}
//Add Vertex Method
public void addVertex(V vid) {
vertices.add(vid);
LinkedHashSet<V> neighborV = new LinkedHashSet<V>();
neighbors.put(vid, neighborV);
neighborsView.put(vid, Collections.unmodifiableSet(neighborV));
}
// Removes Vertex Method
public void removeVertex(V vid) {
if(vertices.remove(vid)) {
LinkedHashSet<V> neighborV = neighbors.remove(vid);
for(V uid : neighborV) {
LinkedHashSet<V> neighborU = neighbors.get(uid);
neighborU.remove(vid);
--edgeCount;
}
neighborsView.remove(vid);
} else {
throw new NoSuchElementException("no such vertex");
}
}
//Add Edge Method
public void addEdge(V uid, V vid) {
LinkedHashSet<V> neighborU = neighbors.get(uid);
LinkedHashSet<V> neighborV = neighbors.get(vid);
if(neighborU == null) throw new NoSuchElementException("first argument not in graph");
if(neighborV == null) throw new NoSuchElementException("second argument not in graph");
if(neighborU.add(vid) && neighborV.add(uid)) {
++edgeCount;
}
}
//Remove Edge Method
public void removeEdge(V uid, V vid) {
LinkedHashSet<V> neighborU = neighbors.get(uid);
LinkedHashSet<V> neighborV = neighbors.get(vid);
if(neighborU == null) throw new NoSuchElementException("first argument not in graph");
if(neighborV == null) throw new NoSuchElementException("second argument not in graph");
if(neighborU.remove(vid) && neighborV.remove(uid)) {
--edgeCount;
} else {
throw new NoSuchElementException("no edge between vertices");
}
}
public void addNeighbor(int neighborV, int neighborU) {
adj.get(neighborV).add(neighborU);
}
public List<Integer> getNeighbors(int v) {
return adj.get(v);
}
public static void main(String[] args) {
try {
File file = new File("data.txt");
InputStreamReader streamReader = new InputStreamReader(
new FileInputStream(file));
BufferedReader br = new BufferedReader(streamReader);
String line = br.readLine();
if (line != null) {
// read nodes
String[] nodeNames = line.split(" ");
int[] nodes = new int[nodeNames.length];
for (int i = 0; i < nodes.length; ++i) {
nodes[i] = Integer.parseInt(nodeNames[i]);
}
// create graph
Graph V = new Graph(nodes);
// read edges
while ((line = br.readLine()) != null) {
String[] tokens = line.split(" ");
int neighborV = Integer.parseInt(tokens[0]);
int neighborU = Integer.parseInt(tokens[1]);
// we add neighbor to each node in both directions.
V.addNeighbor(neighborV, neighborU);
V.addNeighbor(neighborU, neighborV);
}
}
br.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
public Iterator<?> iteratorBFS(Object startVertex) {
return null;
}
public Iterator<?> iteratorDFS(Object startVertex) {
return null;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean isConnected() {
return false;
}
public int size() {
return 0;
}
}
//这里有大量导入(暂时删除)
类图实现GraphADT1{
//每个节点的邻接列表的映射
私有HashMap;
私有数组列表顶点;
私有HashMap邻居;
私有HashMap邻居视图;
私人帐户;
公共图(int[]节点){
顶点=新的ArrayList();
邻居=新的HashMap();
neighborsView=newhashmap();
adj=新的HashMap();
对于(int i=0;i
公共静态void main(字符串[]Args){
试一试{
扫描器s=新扫描器(新文件(“your File.txt”);
StringTokenizer t=新的StringTokenizer(s.nextLine());
Hashtable节点=新的Hashtable();
而(t.hasMoreTokens()){
int id=Integer.parseInt(t.nextToken());
nodes.put(id,新节点(id));
}
而(s.hasnetint()){
Node e1=nodes.get(s.nextInt());
Node e2=nodes.get(s.nextInt());
e1.相邻。添加(e2);
e2.相邻。添加(e1);
}
\\现在,您可以使用上面的节点映射检索节点或获取列表:
List AdjcyNodeList=新的ArrayList(nodes.values());
}catch(filenotfounde异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
类节点{
int-id;
列表相邻=新的ArrayList();
公共节点(int-id){
this.id=id;
}
}
您可以在类中包含图形:
class Graph {
//Map of adjacency lists for each node
Map<Integer, List<Integer>> adj;
public Graph(int[] nodes) {
//your node labels are consecutive integers starting with one.
//to make the indexing easier we will allocate an array of adjacency one element larger than necessary
adj = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < nodes.length; ++i) {
adj.put(i, new LinkedList<Integer>());
}
}
public addNeighbor(int v1, int v2) {
adj.get(v1).add(v2);
}
public List<Integer> getNeighbors(int v) {
return adj.get(v);
}
}
类图{
//每个节点的邻接列表的映射
地图;
公共图(int[]节点){
//节点标签是从一开始的连续整数。
//为了使索引更容易,我们将分配一个邻接数组,比所需的元素大一个
adj=新的HashMap();
对于(int i=0;iclass Graph {
//Map of adjacency lists for each node
Map<Integer, List<Integer>> adj;
public Graph(int[] nodes) {
//your node labels are consecutive integers starting with one.
//to make the indexing easier we will allocate an array of adjacency one element larger than necessary
adj = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < nodes.length; ++i) {
adj.put(i, new LinkedList<Integer>());
}
}
public addNeighbor(int v1, int v2) {
adj.get(v1).add(v2);
}
public List<Integer> getNeighbors(int v) {
return adj.get(v);
}
}
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new StreamReader(System.in));
String line = br.readLine();
if (line != null) {
//read nodes
String[] nodeNames = line.split(" ");
int[] nodes = new int[nodeNames.length]
for (int i = 0; i < nodes.length; ++i) {
nodes[i] = Integer.parseInt(nodeNames[i]);
}
//create graph
Graph g = new Graph(nodes);
//read edges
while((line = br.readLine()) != null) {
String[] tokens = line.split(" ");
int v1 = Integer.parseInt(tokens[0]);
int v2 = Integer.parseInt(tokens[1]);
//we add neighbor to each node in both directions.
g.addNeighbor(v1, v2);
g.addNeighbor(v2, v1);
}
}
br.close();
}
catch(exceptions) {
handle them
}
}