这里的图的深度优先算法利用了栈来实现。
图的深度遍历原则:
1 如果有可能,访问一个领接的未访问的节点,标记它,并把它放入栈中。
2 当不能执行规则 1 时,如果栈不为空,则从栈中弹出一个元素。
3 如果不能执行规则 1 和规则 2 时,则完成了遍历。
代码中的图使用的是Graph 图-邻接矩阵法 来表示,其他的表示法请见:Graph 图-邻接表法
代码中的Stack为辅助结构,用来记载访问过的节点。栈的详细描述可以见:ArrayStack 栈 ,LinkedStack 栈 。
Vertex表示图中的节点,其中包含访问,是否访问,清除访问标志的方法。
Graph.main:提供简单测试。代码可以以指定下标的节点开始作深度遍历。
代码比较简单,除了Graph.dsf(int i)深度优先遍历算法外没有过多注释。
代码如下:
class Stack {
private int[] values;
private int pos = -1;
Stack(int size) {
values = new int[size];
}
void push(int value) { values[++pos] = value; }
int pop() { return values[pos--]; }
int peek() { return values[pos]; }
boolean isEmpty() { return pos == -1; }
}
class Vertex {
private Object value;
private boolean isVisited;
Vertex(Object value) {
this.value = value;
}
void visit() { isVisited = true; print(); }
void clean() { isVisited = false; }
boolean isVisited() { return isVisited; }
void print() { System.out.println(value); }
}
class Graph {
private Vertex[] vertexs;
private int[][] adjMat;
private int pos = -1;
Graph(int size) {
vertexs = new Vertex[size];
adjMat = new int[size][size];
}
void add(Object value) {
assert pos < vertexs.length;
vertexs[++pos] = new Vertex(value);
}
void connect(int from, int to) {
adjMat[from][to] = 1;
adjMat[to][from] = 1;
}
void disConnect(int from, int to) {
adjMat[from][to] = 0;
adjMat[to][from] = 0;
}
int findNeighbor(int index) {
for(int i=0; i<=pos; i++) {
if(adjMat[index][i] == 1 && !vertexs[i].isVisited()) return i;
}
return -1;
}
void dsf(int index) { //从指定下标的节点开始深度优先遍历
if(vertexs[index] == null) return; //如果图中没有指定下标节点,则退出
Stack s = new Stack(vertexs.length); //创建栈记载访问过的节点的下标
vertexs[index].visit(); //访问0节点
s.push(index); //记录0节点
while(!s.isEmpty()) { //如果还有记录的节点则继续
index = findNeighbor(s.peek()); //寻找栈顶节点的未访问过的邻居
if(index != -1) { //如果找到
vertexs[index].visit(); //访问该节点
s.push(index); //记录该节点
} else s.pop(); //没有未访问过的节点,则出栈
} //如果栈未空则代表遍历完成
clean(); //清除所有访问标致
}
void clean() { for(Vertex v: vertexs) if(v != null)v.clean(); }
public static void main(String[] args) {
Graph g = new Graph(20);
g.add('a');
g.add('b');
g.add('c');
g.add('d');
g.add('e');
g.connect(0,1);
g.connect(1,2);
g.connect(0,3);
g.connect(3,4);
g.dsf(4);
}
}

492

被折叠的 条评论
为什么被折叠?



