如上如的所示,对图节点进行编号,每个节点又有相应的编号和值。因此图可以有一个二阶矩阵来记录各个节点的联通关系,由一个数组来记录各个节点的内容。图的广度优先遍历和深度优先遍历。
输出如下:
深度优先遍历:
1
2
4
8
5
6
3
7
广度优先遍历:
1
2
3
4
5
6
7
8
代码如下:
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
/**
* 图的邻接矩阵表示
* 图的广度优先遍历和深度优先遍历
*
@author
liyiwen1
*
@date
2017/1/17
*/
public class Graph {
//存储节点的连接关系
int[][]
connectRelation;
//节点的内容
int[]
content;
public static void main(String[] args) {
int[][] connectRelation =
new int[][]{
{
0,
1,
1,
0,
0,
0,
0,
0},
{
1,
0,
0,
1,
1,
0,
0,
0},
{
1,
0,
0,
0,
0,
1,
1,
0},
{
0,
1,
0,
0,
0,
0,
0,
1},
{
0,
1,
0,
0,
0,
0,
0,
1},
{
0,
0,
1,
0,
0,
0,
0,
1},
{
0,
0,
1,
0,
0,
0,
0,
1},
{
0,
0,
0,
1,
1,
1,
1,
0}
};
int[] content =
new int[]{
1,
2,
3,
4,
5,
6,
7,
8};
Graph graph1 =
new Graph();
graph1.setConnectRelation(connectRelation);
graph1.setContent(content);
System.
out.println(
"深度优先遍历:");
graph1.depthFirstSearch();
System.
out.println(
"广度优先遍历:");
graph1.breadthFirstSearch();
}
//广度优先遍历
public void breadthFirstSearch(){
Deque deque =
new ArrayDeque();
deque.offer(
0);
boolean[] visited =
new boolean[
this.
content.
length];
//记录节点是否已经被访问
while (!deque.isEmpty()){
int node = (Integer)deque.pollFirst();
if (visited[node] ==
false){
System.
out.println(
this.
content[node]);
visited[node] =
true;
for (
int i =
0; i <
this.
content.
length ; ++i){
if (
this.
connectRelation[node][i] ==
1){
deque.offer(i);
}
}
}
}
}
//深度优先遍历
public void depthFirstSearch(){
boolean[] visited =
new boolean[
this.
content.
length];
//记录节点是否已经被访问
depthFirstSearch(visited,
0);
}
public void depthFirstSearch(
boolean[] visited,
int node){
if (visited[node] ==
false){
//如果节点未被访问
System.
out.println(
this.
content[node]);
visited[node] =
true;
for (
int i =
0; i <
this.
content.
length; ++i){
if (
this.
connectRelation[node][i] ==
1){
depthFirstSearch(visited, i);
}
}
}
}
public int[][] getConnectRelation() {
return
connectRelation;
}
public void setConnectRelation(
int[][] connectRelation) {
this.
connectRelation = connectRelation;
}
public int[] getContent() {
return
content;
}
public void setContent(
int[] content) {
this.
content = content;
}
}