利用二维数组、Map或Graph类存储有向图,并完成如下操作: 输入:图的任意一个节点编号; 输出:该节点的入度、出度、入度边邻居和出度边邻居的编号。
时间: 2024-05-12 21:13:01 浏览: 7
可以使用Map类存储有向图,其中key为节点编号,value为该节点的出边邻居编号列表。同时,可以再创建一个Map类存储每个节点的入度边邻居编号列表。以下是代码实现:
```
import java.util.*;
public class DirectedGraph {
private Map<Integer, List<Integer>> adjList;
private Map<Integer, List<Integer>> inEdges;
public DirectedGraph() {
adjList = new HashMap<>();
inEdges = new HashMap<>();
}
public void addNode(int node) {
if (!adjList.containsKey(node)) {
adjList.put(node, new ArrayList<>());
inEdges.put(node, new ArrayList<>());
}
}
public void addEdge(int from, int to) {
addNode(from);
addNode(to);
adjList.get(from).add(to);
inEdges.get(to).add(from);
}
public int getIndegree(int node) {
if (!inEdges.containsKey(node)) {
return 0;
}
return inEdges.get(node).size();
}
public int getOutdegree(int node) {
if (!adjList.containsKey(node)) {
return 0;
}
return adjList.get(node).size();
}
public List<Integer> getInEdges(int node) {
if (!inEdges.containsKey(node)) {
return new ArrayList<>();
}
return inEdges.get(node);
}
public List<Integer> getOutEdges(int node) {
if (!adjList.containsKey(node)) {
return new ArrayList<>();
}
return adjList.get(node);
}
public static void main(String[] args) {
DirectedGraph graph = new DirectedGraph();
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(3, 4);
int node = 3;
System.out.println("Indegree of node " + node + ": " + graph.getIndegree(node));
System.out.println("Outdegree of node " + node + ": " + graph.getOutdegree(node));
System.out.println("InEdges of node " + node + ": " + graph.getInEdges(node));
System.out.println("OutEdges of node " + node + ": " + graph.getOutEdges(node));
}
}
```
输出结果为:
```
Indegree of node 3: 2
Outdegree of node 3: 1
InEdges of node 3: [1, 2]
OutEdges of node 3: [4]
```