33,008
社区成员
发帖
与我相关
我的任务
分享
class Stack1 {
private int[] values;
private int pos = -1;
Stack1(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 Stack2 {
private int[] values;
private int pos = -1;
Stack2(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 Vertex1 {
boolean isVisited;
private char value;
private int id;
char[][] array = new char[5][];
Vertex1(char value, int id) {
this.value = value;
this.id = id;
}
void visit() {
isVisited = true;
print();
}
void print() {
System.out.print(value);
System.out.print(id);
}
boolean isVisited() {
return isVisited;
}
void clean() {
isVisited = false;
}
public char getValue() {
return value;
}
public int id() {
return id;
}
}
class Graph1 {
private Vertex1[] vertexs;
private int[][] adjMat;
private int pos = -1;
Graph1(int size) {
vertexs = new Vertex1[size];
adjMat = new int[size][size];
}
void add(char value, int id) {
assert pos < vertexs.length;
vertexs[++pos] = new Vertex1(value, id);
}
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 dfs(int index) {
if(vertexs[index] == null) {
return;
}
Stack1 s = new Stack1(vertexs.length);
vertexs[index].visit();
s.push(index);
while(!s.isEmpty()) {
index = findNeighbor(s.peek());
if (index !=-1) {
vertexs[index].visit();
s.push(index);
}
else
s.pop();
}
clean();
}
//啥意思
void clean() {
for(Vertex1 v : vertexs)
if(v != null)
v.clean();
}
public static void main(String[] args) {
Graph1 g = new Graph1(20);
g.add('a', 0);
g.add('b', 1);
g.add('c', 2);
g.add('d', 3);
g.add('e', 4);
g.connect(0, 1);
g.connect(0, 2);
g.connect(2, 3);
g.connect(1, 3);
g.connect(3, 4);
for(int i=0; i <5; i++){
g.dfs(i);
System.out.println("");
}
}
}