package Graph;
import java.io.IOException;
import java.util.Queue;
import java.util.Scanner;
class GraphNode{
int data;
}
public class Graph {
GraphNode vexs[]=new GraphNode[100]; //图的结点表
int[][] arcs=new int[100][100]; //邻接矩阵(0为无边,1为有边)
int vexnum,arcnum; //顶点数和边数
Graph() {
//对象数组出现空指针异常:必须逐个初始化
for (int i = 0; i < vexs.length; i++) {
vexs[i]=new GraphNode();
}
}
public void create() { //创建图
System.out.println("请输入点数和边数(输入一个换一行)");
Scanner sc=new Scanner(System.in);
vexnum=sc.nextInt();
arcnum=sc.nextInt();
System.out.println("请依次输入结点的数据(请记住每个结点的序号),用一行相邻字符输入:");
for (int i = 0; i < vexnum; i++) {
try {
vexs[i].data=(char)System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("请输入每条边相连俩个结点的序号");
for (int i = 0; i < arcnum; i++) {
int x=sc.nextInt();
int y=sc.nextInt();
arcs[x-1][y-1]=1; //构建邻接矩阵(序号=索引+1)
arcs[y-1][x-1]=1;
}
}
/*
* 非递归比递归节省时间,此递归相当于每个结点都用for走了一遍
*/
//图非递归深搜
public void DFSOne(int v) {
OrderStack stack = new OrderStack(vexnum*vexnum);
int judge[]=new int[vexnum]; //判断结点是否被访问(0未访问,1已访问)
int size=0; //计数(已访问结点)
int t=-1; //临时变量
while (size!=vexnum) {
if (v==t) { //当前结点没有相连且未访问结点
stack.pull(); //退出该结点
v=(int) stack.getTop(); //返回上一结点
}else { //当前结点有相连且未访问结点
char c[]=new char[]{(char) vexs[v].data};
System.out.println(new String(c));
stack.push(v); //入栈
judge[v]=1;
size++;
}
t=v; //不论是刚退栈的结点v,还是处在深搜的结点v都需要进行如下t的检验
for (int i = 0; i < vexnum; i++) {
if (arcs[v][i]!=0&&judge[i]!=1) { //找到第一个未访问且相连结点
v=i;
break;
}
}
}
}
//图的递归深搜
int judge[]=new int[100]; //判断当前结点是否被访问,因为是递归方法,
//所以需要在方法外部建立数组
public void DFSTwo(int v) {
if (judge[v]!=1) {
char c[]=new char[]{(char) vexs[v].data};
System.out.println(new String(c));
judge[v]=1;
}
for (int i = 0; i < vexnum; i++) {
if (arcs[v][i]==1&&judge[i]==0) { //连通且未访问结点
DFSTwo(i);
}
}
}
//图的广度搜索
public void BFS(int v) {
int judge[]=new int[vexnum]; //判断结点是否被访问(0未访问,1已访问)
OrderQueue oq=new OrderQueue(vexnum);
oq.entry(v);
while (oq.getStart()!=null) {
v=(int) oq.exit();
char c[]=new char[]{(char) vexs[v].data};
System.out.println(new String(c));
judge[v]=1;
for (int i = 0; i < vexnum; i++) {
if(arcs[v][i]==1&&judge[i]!=1) {
oq.entry(i);
}
}
}
}
}
测试:
package Graph;
/*
* 测试数据:
第一组:
5
7
abcde
1 2
1 3
1 4
2 3
2 5
3 5
4 5
第二组:
5
4
12345
1 3
2 3
3 5
5 4
*/
public class test {
public static void main(String[] args) {
Graph graph=new Graph();
graph.create();
for(int i=0;i<graph.vexnum;i++) {
for(int j=0;j<graph.vexnum;j++) {
System.out.print(graph.arcs[i][j]+" ");
}
System.out.println();
}
graph.DFSOne(2);
graph.DFSTwo(2);
graph.BFS(3);
}
}