先决条件:图形及其表示
在本文中,我们将讨论在Java使用 ArrayList 的 Graph 邻接列表表示。
以下是上图的邻接表表示。
这个想法是使用ArrayLists的ArrayList。
// Java code to demonstrate Graph representation
// using ArrayList in Java
import java.util.*;
class Test {
static void addEdge(ArrayList > adj,
int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void printAdjacencyList(ArrayList > adj)
{
for (int i = 0; i < adj.size(); i++) {
System.out.println("Adjacency list of " + i);
for (int j = 0; j < adj.get(i).size(); j++) {
System.out.print(adj.get(i).get(j) + " ");
}
System.out.println();
}
}
public static void main(String[] args)
{
// Creating a graph with 5 vertices
int V = 5;
ArrayList > adj = new ArrayList >(V);
for (int i = 0; i < V; i++)
adj.add(new ArrayList());
// Adding edges one by one.
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
printAdjacencyList(adj);
}
}
输出:
Adjacency list of 0
1 4
Adjacency list of 1
0 2 3 4
Adjacency list of 2
1 3
Adjacency list of 3
1 2 4
Adjacency list of 4
0 1 3
使用单独的图形类的类似实现。
// Java code to demonstrate Graph representation
// using ArrayList in Java
import java.util.*;
class Graph {
ArrayList > adj;
int V;
Graph(int v)
{
V = v;
adj = new ArrayList >(V);
for (int i = 0; i < V; i++)
adj.add(new ArrayList());
}
void addEdge(int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
void printAdjacencyList()
{
for (int i = 0; i < adj.size(); i++) {
System.out.println("Adjacency list of " + i);
for (int j = 0; j < adj.get(i).size(); j++) {
System.out.print(adj.get(i).get(j) + " ");
}
System.out.println();
}
}
}
class Test {
public static void main(String[] args)
{
// Creating a graph with 5 vertices
int V = 5;
Graph g = new Graph(V);
// Adding edges one by one.
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
g.printAdjacencyList();
}
}
输出:
Adjacency list of 0
1 4
Adjacency list of 1
0 2 3 4
Adjacency list of 2
1 3
Adjacency list of 3
1 2 4
Adjacency list of 4
0 1 3
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。