# 有向图的邻接表和邻接矩阵

14 篇文章 0 订阅

### 邻接表

A -> B, C
B -> C, D
C -> D
D -> A


A: [B, C]
B: [C, D]
C: [D]
D: [A]


java表示这样的邻接表：

import java.util.*;

public class DirectedGraph {

public DirectedGraph() {

}

public void addEdge(String source, String target) {

}

public List<String> getNeighbors(String node) {

}

public static void main(String[] args) {

DirectedGraph graph = new DirectedGraph();

for (String node : graph.adjacencyList.keySet()) {

List<String> neighbors = graph.getNeighbors(node);

System.out.print(node + " -> ");

for (String neighbor : neighbors) {

System.out.print(neighbor + " ");

}

System.out.println();

}

}
}
}


### 邻接矩阵

cssCopy code
A -> B
A -> C

B -> C

B -> D
C
C -> D
D
D -> A

cssCopy code
A B C D

A 0 1 1 0
B 0 0 1 1
C
C 0 0 0 1
D
D 1 0 0 0

javaCopy code

{0, 1, 1, 0},

{0, 0, 1, 1},

{0, 0, 0, 1},

{1, 0, 0, 0}


}
};

javaCopy code
public class DirectedGraph {

private int[][] adjMatrix;

private int numNodes;

public DirectedGraph(int numNodes) {

this.numNodes = numNodes;

}

public void addEdge(int source, int target) {

}

public void removeEdge(int source, int target) {

}

public boolean hasEdge(int source, int target) {

}

public int getNumNodes() {

return numNodes;

}

for (int i = 0; i < numNodes; i++) {

for (int j = 0; j < numNodes; j++) {

}

System.out.println();

}

}

public static void main(String[] args) {

DirectedGraph graph = new DirectedGraph(4);

}


}
}

• 4
点赞
• 1
收藏
觉得还不错? 一键收藏
• 0
评论
07-16
03-29 912
09-08 1万+
10-08 3674
02-16 4630
12-04 973
12-24 6万+
06-25
11-27

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。