图 的矩阵表示 和邻接表表示
代码
邻接矩阵
package Graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Graph {
final int Maxsize=10;
final int Max=999;
int[][] arcs;
int[] v;
int e;
int n;
boolean[] found;
public Graph() {
v=new int[Maxsize];
arcs=new int[Maxsize][Maxsize];
}
public Graph(int n,int e) {
this();
this.e=e;
this.n=n;
found=new boolean[n];
}
//增加无向边
public void addEdge(String str) {
int v1=str.charAt(0)-48;
int v2=str.charAt(1)-48;
arcs[v1][v2]=1;
arcs[v2][v1]=1;
}
//增加有向边
public void addDirectedEdge(String str) {
int v1=str.charAt(0)-48;
int v2=str.charAt(1)-48;
arcs[v1][v2]=1;
}
public void DisplayAdjMatrix() {
int i,j;
System.out.println("图的邻接矩阵表示:");
for(i=0;i<n;i++) {
for(j=0;j<n;j++) {
System.out.print(" "+arcs[i][j]);
}
System.out.println();
}
}
public void BFS(int s) {
boolean visited[] =new boolean[n];
visited[s]=true;
Queue<Integer> queue=new LinkedList<Integer>();
queue.add(s);
while(!queue.isEmpty()) {
int w=queue.poll();
System.out.print(w+" ");
for (int i = 0; i < n; i++) {
if(arcs[w][i]==1 && visited[i]==false) {
visited[i]=true;
queue.add(i);
}
}
}
}
public void DFS(int s) {
found[s]=true;
System.out.print(s+" ");
for(int i=0;i<n;i++) {
if(arcs[s][i]==1 && found[i]==false) {
DFS(i);
}
}
}
//测试
public static void main(String[] args) {
Graph G=new Graph(5,8);
String[] string = new String[] {
"01","03","04","12","13","23","24","34"
};
for(int i=0;i<string.length;i++) {
G.addEdge(string[i]);
}
G.DisplayAdjMatrix();
G.BFS(0);
System.out.println();
G.DFS(0);
}
}
邻接表
package Graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class ADJGraph {
private int v;
private LinkedList<Integer> adj[];
private boolean[] found;
public ADJGraph(int n) {
this.v=n;
adj=new LinkedList[n];
found=new boolean[n];
for(int i=0;i<v;i++) {
adj[i]=new LinkedList<Integer>();
}
}
public void addEdge(String str) {
int s = str.charAt(0)-48;
int t = str.charAt(1)-48;
adj[s].add(t);
adj[t].add(s);
}
public void addDirectedEdge(String str) {
int s = str.charAt(0)-48;
int t = str.charAt(1)-48;
adj[s].add(t);
}
public void BFS(int s) {
boolean visited[] =new boolean[v];
visited[s]=true;
System.out.print(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 q=adj[w].get(i);
if(!visited[q]) {
visited[q]=true;
System.out.print(q+" ");
queue.add(q);
}
}
}
}
public void DFS(int s) {
found[s]=true;
System.out.print(s+" ");
for (int i = 0; i < adj[s].size(); i++) {
int q=adj[s].get(i);
if(!found[q]) {
DFS(q);
}
}
}
public static void main(String[] args) {
ADJGraph graph = new ADJGraph(5);
String[] string = new String[] {
"01","03","04","12","13","23","24","34"
};
for(int i=0;i<string.length;i++) {
graph.addEdge(string[i]);
}
for (int i = 0; i < graph.v; i++) {
System.out.println(graph.adj[i]);
}
graph.BFS(0);
System.out.println();
graph.DFS(0);
}
}