---
title: "Graph data structure"
author: "willpower"
date: "2007-03-23T12:04:05Z"
tags: []
slug: "graph-data-structure"
draft: false
lastmod: "2007-03-23T12:04:05Z"
id: 64907
url: "https://willpower.iteye.com/blog/64907"
---

1\. adjacent matrix

good for border scan, bad for space O(n\*n), spare matrix mostly

java 代码

01. public class GraphMatrix {
02. private int\[]\[] nodeMatrix;
03. private int matrixSize;
04. public GraphMatrix(int matrixSize) {
05. this.matrixSize = matrixSize;
06. nodeMatrix = new int\[matrixSize]\[matrixSize];
07. init();
08. }
09. private void init() {
10. for (int i=0; i
11. for (int j=0; j
12. nodeMatrix\[i]\[j] = 0;
13. }
14. }
15. }
16. public boolean addBorder(int startNode, int endNode) {
17. if (hasBorder(startNode, endNode)) {
18. System.err.println("already has a border!!!");
19. return false;
20. }
21. nodeMatrix\[startNode]\[endNode] = 1;
22. return true;
23. }
24. public boolean hasBorder(int startNode, int endNode) {
25. if (nodeMatrix\[startNode]\[endNode] == 1) {
26. return true;
27. }
28. return false;
29. }
30. public boolean deleteBorder(int startNode, int endNode) {
31. if (!hasBorder(startNode, endNode)) {
32. System.err.println("no this border!!!");
33. return false;
34. }
35. nodeMatrix\[startNode]\[endNode] = 0;
36. return true;
37. }
38. }

2\. adjacent table/vector

good for space, bad for border scan

java 代码

01. import java.util.Vector;
02. public class GraphTable {
03. class Node {
04. Vector adjacentNodes =  new Vector();
05. public void add(Node node) {
06. if (!hasNode(node)) {
07. adjacentNodes.add(node);
08. }
09. }
10. public boolean hasNode(Node node) {
11. return adjacentNodes.contains(node);
12. }
13. public void delete(Node node) {
14. if (hasNode(node)) {
15. adjacentNodes.remove(node);
16. }
17. }
18. }
19. private Node\[] nodeTable;
20. private int tableSize;
21. public GraphTable(int tableSize) {
22. this.tableSize = tableSize;
23. nodeTable = new Node\[tableSize];
24. init();
25. }
26. private void init() {
27. for (int i=0; i
28. nodeTable\[i] = new Node();
29. }
30. }
31. public void addBorder(int fromNode, int desNode) {
32. nodeTable\[desNode].add(nodeTable\[fromNode]);
33. }
34. public void deleteBorder(int desNode, int deleteNode) {
35. nodeTable\[desNode].delete(nodeTable\[deleteNode]);
36. }
37. public boolean hasBorder(int fromNode, int toNode) {
38. return nodeTable\[fromNode].hasNode(nodeTable\[toNode]);
39. }
40. }

3\. incident matrix

n/a