一、图的深度优先遍历(邻接矩阵)
- 定义一个变量 vn 记录顶点数。
- 定义一个顶点一维数组 vertices 用于记录顶点名。
- 定义一个二维数组 graph ,也就是邻接矩阵。
- 定义一个一维数组 visited 记录顶点的访问情况。
- 定义一个二维i数组 edges 记录顶点之间的关系,也就是图中存在的边。(也可以直接从实际情况总结出图中的边的连接情况)
1、递归法
for (int i = 0; i < vn; i++){
dfsGraphTravel.dfsTravel(i);
}
class DFSGraphTravel{
int vn;
private int[][] edges;
private boolean[] visited;
private int[][] graph;
private String[] vertices;
public DFSGraphTravel(int vn, int[][] edges, String[] vertices){
this.vn = vn;
this.visited = new boolean[vn];
for (int i = 0; i < vn; i++){
this.visited[i] = false;
}
this.vertices = vertices;
this.edges = edges;
graph = new int[vn][vn];
for (int i = 0; i < edges.length; i++){
int start = edges[i][0];
int end = edges[i][1];
graph[start][end] = 1;
}
}
public void dfsTravel(int v){
if (visited[v]){
return;
}
visit(v);
visited[v] = true;
for (int j = 0; j < vn; j++){
if (graph[v][j] == 1 && !visited[j]){
visit(j);
visited[j] = true;
dfsTravel(j);
}
}
}
public void visit(int v){
System.out.print(vertices[v] + " ");
}
}
2、借助栈的非递归法
class DFSGraphTravelByStack{
int vn;
private int[][] edges;
private boolean[] visited;
private int[][] graph;
private String[] vertices;
public DFSGraphTravelByStack(int vn, int[][] edges, String[] vertices){
this.vn = vn;
this.visited = new boolean[vn];
for (int i = 0; i < vn; i++){
this.visited[i] = false;
}
this.vertices = vertices;
this.edges = edges;
graph = new int[vn][vn];
for (int i = 0; i < edges.length; i++){
int start = edges[i][0];
int end = edges[i][1];
graph[start][end] = 1;
}
}
public void dfsTravelByStack(){
Stack<Integer> stack = new Stack<>();
for (int v = 0; v < vn; v++){
if (!visited[v]){
visited[v] = true;
visit(v);
stack.push(v);
}
while (!stack.isEmpty()){
int temp = stack.pop();
for (int j = 0; j < vn; j++){
if (graph[temp][j] == 1 && !visited[j]){
visit(j);
visited[j] = true;
stack.push(j);
break;
}
}
}
}
}
public void visit(int v){
System.out.print(vertices[v] + " ");
}
}
二、图的广度优先遍历(邻接矩阵法)
1、借助队列的非递归方法
for (int i = 0; i < vn; i++){
bfsGraphTravelByQueue.bfsTravelByQueue(i);
}
class BFSGraphTravelByQueue{
int vn;
private int[][] edges;
private boolean[] visited;
private int[][] graph;
private String[] vertices;
public BFSGraphTravelByQueue(int vn, int[][] edges, String[] vertices){
this.vn = vn;
this.visited = new boolean[vn];
for (int i = 0; i < vn; i++){
this.visited[i] = false;
}
this.vertices = vertices;
this.edges = edges;
graph = new int[vn][vn];
for (int i = 0; i < edges.length; i++){
int start = edges[i][0];
int end = edges[i][1];
graph[start][end] = 1;
}
}
public void bfsTravelByQueue(int v){
if (visited[v]){
return;
}
visit(v);
visited[v] = true;
Queue<Integer> queue = new LinkedList<>();
queue.offer(v);
while (!queue.isEmpty()){
int temp = queue.poll();
for (int j = 0; j < vn; j++){
if (graph[temp][j] == 1 && !visited[j]){
visit(j);
visited[j] = true;
queue.offer(j);
}
}
}
}
public void visit(int v){
System.out.print(vertices[v] + " ");
}
}