public class ADJGraph {
private int v;
private LinkedList<Integer> adj[];
private boolean found[];
public ADJGraph(int v) {
this.v = v;
//初始化--在链表中循环嵌套
adj = new LinkedList[v];
for (int i = 0; i < adj.length; i++) {
adj[i] = new LinkedList<Integer>();}
found=new boolean[v];
}
public void addEdge(int s,int t ) {
//调用链表的add方法,将图的纵,横边数据加入图
adj[s].add(t);
adj[t].add(s);
}
//广度优先遍历类似层次遍历
public void bfs(int s) {
//boolean数组存储数据,默认s=true
boolean[] visited = new boolean[v];
visited[s] = true;
System.out.print(s+" ");
//队列的借口,链表形式,首先添加第一个s
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(s);
//在确定队列不为空的情况下,出一个,入队一次
while (!queue.isEmpty()) {
int w = queue.poll();
//遍历
for (int i = 0; i <adj[w].size(); i++) {
int p=adj[w].get(i);
if (!visited[p]) {
visited[p]=true;
System.out.print(p+" ");
queue.add(p);
}
}
}
System.out.println(" ");
}
//深度优先遍历类似于先序遍历,递归
public void dfs(int s) {
//s默认为TRUE
found[s] = true;
System.out.print(s+" ");
//循环遍历出元素
for (int i = 0; i < adj[s].size(); i++) {
int q = adj[s].get(i);//get方法将每个值拿出来
if (!found[q]) {
dfs(q);//没有访问过就直接递归
}
}
}
public static void main(String[] args) {
ADJGraph graph = new ADJGraph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 3);
graph.addEdge(0, 4);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
for (int i = 0; i < graph.v; i++) {
System.out.println("["+i+"]"+"对应的链表为:"+graph.adj[i]);
}
System.out.println("广度优先遍历:");
graph.bfs(0);
System.out.println("深度优先遍历:");
graph.dfs(0);
}
}