1,相当于图的压缩存储. 每一行数据用一个单链表存储.
2,重写了广度优先遍历. 可以发现, 使用队列的机制不变. 仅仅是把其中的 for 循环换成了 while, 避免检查不存在的边. 如果图很稀疏的话, 可以降低时间复杂度.
package java31to40;
import java21to30.D22_CircleObjectQueue;
public class D36_AdjacencyList {
class AdjacencyNode {
int column;
AdjacencyNode next;
public AdjacencyNode(int paraColumn) {
column = paraColumn;
next = null;
}
}
int numNodes;
AdjacencyNode[] headers;
public D36_AdjacencyList(int[][] paraMatrix) {
numNodes = paraMatrix.length;
AdjacencyNode tempPreviousNode, tempNode;
headers = new AdjacencyNode[numNodes];
for (int i = 0; i < numNodes; i++) {
headers[i] = new AdjacencyNode(-1);
tempPreviousNode = headers[i];
for (int j = 0; j < numNodes; j++) {
if (paraMatrix[i][j] == 0) {
continue;
}
tempNode = new AdjacencyNode(j);
tempPreviousNode.next = tempNode;
tempPreviousNode = tempNode;
}
}
}
public String toString() {
String resultString = "";
AdjacencyNode tempNode;
for (int i = 0; i < numNodes; i++) {
tempNode = headers[i].next;
while (tempNode != null) {
resultString += " (" + i + ", " + tempNode.column + ")";
tempNode = tempNode.next;
}
resultString += "\r\n";
}
return resultString;
}
public String breadthFirstTraversal(int paraStartIndex) {
D22_CircleObjectQueue tempQueue = new D22_CircleObjectQueue();
String resultString = "";
boolean[] tempVisitedArray = new boolean[numNodes];
tempVisitedArray[paraStartIndex] = true;
tempVisitedArray[paraStartIndex] = true;
resultString += paraStartIndex;
tempQueue.enqueue(new Integer(paraStartIndex));
int tempIndex;
Integer tempInteger = (Integer) tempQueue.dequeue();
AdjacencyNode tempNode;
while (tempInteger != null) {
tempIndex = tempInteger.intValue();
tempNode = headers[tempIndex].next;
while (tempNode != null) {
if (tempVisitedArray[tempNode.column]) {
continue;
}
tempVisitedArray[tempNode.column] = true;
resultString += tempNode.column;
tempQueue.enqueue(new Integer(tempNode.column));
tempNode = tempNode.next;
}
tempInteger = (Integer) tempQueue.dequeue();
}
return resultString;
}
public static void breadthFirstTraversalTest() {
int[][] tempMatrix = { { 0, 1, 1, 0 }, { 1, 0, 0, 1 }, { 1, 0, 0, 1 }, { 0, 1, 1, 0 } };
D32_Graph tempGraph = new D32_Graph(tempMatrix);
System.out.println(tempGraph);
String tempSequence = "";
try {
tempSequence = tempGraph.breadthFirstTraversal(2);
} catch (Exception ee) {
System.out.println(ee);
}
System.out.println("广度优先访问顺序: " + tempSequence);
}
public static void main(String[] args) {
int[][] tempMatrix = { { 0, 1, 0 }, { 1, 0, 1 }, { 0, 1, 0 } };
D36_AdjacencyList tempTable = new D36_AdjacencyList(tempMatrix);
System.out.println("数据是:\r\n" + tempTable);
breadthFirstTraversalTest();
}
}
结果输出:
数据是:
(0, 1)
(1, 0) (1, 2)
(2, 1)
图的连通性矩阵.
[[0, 1, 1, 0], [1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 1, 0]]
广度优先访问顺序: 2031