ITeye博客

Graph data structure

willpower · 2007-03-23 12:04 · Study 学习 · Markdown

1. adjacent matrix

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

java 代码

  1. public class GraphMatrix {
  2. private int[][] nodeMatrix;
  3. private int matrixSize;
  4. public GraphMatrix(int matrixSize) {
  5. this.matrixSize = matrixSize;
  6. nodeMatrix = new int[matrixSize][matrixSize];
  7. init();
  8. }
  9. 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 代码

  1. import java.util.Vector;
  2. public class GraphTable {
  3. class Node {
  4. Vector adjacentNodes =  new Vector();
  5. public void add(Node node) {
  6. if (!hasNode(node)) {
  7. adjacentNodes.add(node);
  8. }
  9. }
  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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。