问题描述
- 用java建立无向图,然后进行深度和广度遍历,下列的代码怎么改
- import java.util.LinkedList;
import java.util.Queue;
class MatrixUDG {
static int vlen;
int elen;
int[][] mMatrix;
char[] mVexs;
private int number = 7;
private boolean[] flag;
int[][] edges;
MatrixUDG(char[] vexs char[][] edges) {
// 初始化""顶点数""和""边数""
int vlen = vexs.length;
int elen = edges.length;
// 初始化""顶点""
mVexs = new char[vlen];
for (int i = 0; i < mVexs.length; i++)
mVexs[i] = vexs[i];
// 初始化""边""
mMatrix = new int[vlen][vlen];
this.edges = new int[vlen][vlen];
for (int i = 0; i < elen; i++) {
// 读取边的起始顶点和结束顶点
int p1 = getPosition(edges[i][0]);
int p2 = getPosition(edges[i][1]);
// mMatrix[p1][p2] = 1;
// mMatrix[p2][p1] = 1;this.edges[p1][p2] = 1; this.edges[p1][p2] = 1; } flag = new boolean[vlen];}/* * 返回ch位置 */int getPosition(char ch) { for (int i = 0; i < mVexs.length; i++) if (mVexs[i] == ch) return i; return -1;}public void print() { System.out.printf(""Martix Graph:n""); for (int i = 0; i < mVexs.length; i++) { for (int j = 0; j < mVexs.length; j++) System.out.printf(""%d "" mMatrix[i][j]); System.out.printf(""n""); }}void DFSTraverse() { flag = new boolean[number]; for (int i = 0; i < number; i++) { if (flag[i] == false) {// 当前顶点没有被访问 DFS(i); } }}void DFS(int i) { flag[i] = true;// 第i个顶点被访问 System.out.print(mVexs[i] + "" ""); for (int j = 0; j < number; j++) { if (flag[j] == false && edges[i][j] == 1) { DFS(j); } }}void BFSTraverse() { flag = new boolean[number]; Queue<Integer> queue = new LinkedList<Integer>(); for (int i = 0; i < number; i++) { if (flag[i] == false) { flag[i] = true; System.out.print(mVexs[i] + "" ""); queue.add(i); while (!queue.isEmpty()) { int j = queue.poll(); for (int k = 0; k < number; k++) { if (edges[j][k] == 1 && flag[k] == false) { flag[k] = true; System.out.print(mVexs[k] + "" ""); queue.add(k); } } } } }}
}
class Test {
public static void main(String[] args) {
char[] vexs = { 'A' 'B' 'C' 'D' 'E' 'F' 'G' };
char[][] edges = new char[][] { { 'A' 'C' } { 'A' 'D' }
{ 'A' 'F' } { 'B' 'C' } { 'C' 'D' } { 'E' 'G' }
{ 'F' 'G' } };
MatrixUDG t = new MatrixUDG(vexs edges);
t.print(); // 打印图
System.out.println(""图的深度遍历操作:"" + "" "");
t.DFSTraverse();
System.out.println();
System.out.println(""图的广度遍历操作:""+"" "");
t.BFSTraverse();
}
}
解决方案
单步调试下,看看变量是否为null
时间: 2024-11-30 02:24:44