1. adjacent matrix
good for border scan, bad for space O(n*n), spare matrix mostly
java 代码
- public class GraphMatrix {
- private int[][] nodeMatrix;
- private int matrixSize;
- public GraphMatrix(int matrixSize) {
- this.matrixSize = matrixSize;
- nodeMatrix = new int[matrixSize][matrixSize];
- init();
- }
- private void init() {
- for (int i=0; i
- for (int j=0; j
- nodeMatrix[i][j] = 0;
- }
- }
- }
- public boolean addBorder(int startNode, int endNode) {
- if (hasBorder(startNode, endNode)) {
- System.err.println("already has a border!!!");
- return false;
- }
- nodeMatrix[startNode][endNode] = 1;
- return true;
- }
- public boolean hasBorder(int startNode, int endNode) {
- if (nodeMatrix[startNode][endNode] == 1) {
- return true;
- }
- return false;
- }
- public boolean deleteBorder(int startNode, int endNode) {
- if (!hasBorder(startNode, endNode)) {
- System.err.println("no this border!!!");
- return false;
- }
- nodeMatrix[startNode][endNode] = 0;
- return true;
- }
- }
2. adjacent table/vector
good for space, bad for border scan
java 代码
- import java.util.Vector;
- public class GraphTable {
- class Node {
- Vector adjacentNodes = new Vector();
- public void add(Node node) {
- if (!hasNode(node)) {
- adjacentNodes.add(node);
- }
- }
- public boolean hasNode(Node node) {
- return adjacentNodes.contains(node);
- }
- public void delete(Node node) {
- if (hasNode(node)) {
- adjacentNodes.remove(node);
- }
- }
- }
- private Node[] nodeTable;
- private int tableSize;
- public GraphTable(int tableSize) {
- this.tableSize = tableSize;
- nodeTable = new Node[tableSize];
- init();
- }
- private void init() {
- for (int i=0; i
- nodeTable[i] = new Node();
- }
- }
- public void addBorder(int fromNode, int desNode) {
- nodeTable[desNode].add(nodeTable[fromNode]);
- }
- public void deleteBorder(int desNode, int deleteNode) {
- nodeTable[desNode].delete(nodeTable[deleteNode]);
- }
- public boolean hasBorder(int fromNode, int toNode) {
- return nodeTable[fromNode].hasNode(nodeTable[toNode]);
- }
- }
3. incident matrix
n/a