Java通过邻接矩阵实现无向图的创建、遍历(DFS、BFS)
边(弧)
public class ArcCell {
int adj;
String info;
}
关于Graph类:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Graph {
int[] vexs;
ArcCell[][] arcCells;
int vexnum;
int arcnum;
boolean[] visited;
final static int INFINITY = 2147483646;
//创建一个新的无向图
static Graph CreateUDN() {
Scanner sc = new Scanner(System.in);
Graph G = new Graph();
System.out.println("请输入顶点数:");
G.vexnum = sc.nextInt();
System.out.println("请输入边数:");
G.arcnum = sc.nextInt();
G.vexs = new int[G.vexnum];
G.arcCells = new ArcCell[G.vexnum][G.vexnum];
System.out.println("请输入" + G.vexnum + "个顶点的信息:");
for (int i = 0; i < G.vexnum; i++) {
G.vexs[i] = sc.nextInt();
}
for (int i = 0; i < G.vexnum; i++) {
for (int j = 0; j < G.vexnum; j++) {
G.arcCells[i][j] = new ArcCell();
G.arcCells[i][j].adj = INFINITY;
G.arcCells[i][j].info = null;
}
}
System.out.println("请输入" + G.arcnum + "个边的信息:(输入形式:顶点1 顶点2 权值)");
for (int i = 0; i < G.arcnum; i++) {
int a1 = sc.nextInt();
int a2 = sc.nextInt();
int value = sc.nextInt();
int i1 = LocalVex(G, a1);
int j1 = LocalVex(G, a2);
if(i1 != -1 && j1 != -1) {
G.arcCells[i1][j1].adj = value;
G.arcCells[j1][i1].adj = value;
}
}
System.out.println("初始化完成!");
sc.close();
return G;
}
//指定值的位置
static int LocalVex(Graph G, int value) {
for (int i = 0; i < G.vexs.length; i++) {
if(G.vexs[i] == value) {
return i;
}
}
return -1;
}
//下一个点位置
static int NextVex(Graph G, int i, int w) {
for (int j = w + 1; j < G.vexnum; j++) {
if(G.arcCells[i][j].adj != INFINITY && G.visited[j] == false) {
return j;
}
}
return -1;
}
//DFS 通过递归调用实现DFS遍历
//DFS遍历
static void DFSTraverse(Graph G){
G.visited = new boolean[G.vexnum];
for (int i = 0; i < G.vexnum; i++) {
if(!G.visited[i]) {
DFS(G, i);
}
}
}
//DFS方法
static void DFS(Graph G, int i){
G.visited[i] = true;
System.out.print(G.vexs[i] + " ");
for (int w = NextVex(G, i, 0); w>=0; w = NextVex(G, i, w)) {
if(G.visited[w] == false) {
DFS(G, w);
}
}
}
//BFS 通过使用ArrayList模拟队列实现BFS遍历
static void BFSTraverse(Graph G) {
System.out.println();
List<Integer> queue = new ArrayList<Integer>();
G.visited = new boolean[G.vexnum];
for (int i = 0; i < G.vexnum; i++) {
if(!G.visited[i]) {
G.visited[i] = true;
System.out.print(G.vexs[i] + " ");
queue.add(i);
while(!queue.isEmpty()) {
int aaa = queue.remove(0);
for(int w = NextVex(G, aaa, 0);w>=0;w = NextVex(G, aaa, w)) {
if(!G.visited[w]) {
G.visited[w] = true;
System.out.print(G.vexs[w] + " ");
queue.add(w);
}
}
}
}
}
}
}