java - 如何在邻接矩阵的广度优先搜索中跟踪每个顶点的深度?(爪哇)
问题描述
我试图在邻接矩阵的广度优先搜索期间跟踪和打印每个节点的深度。
public class steptwo {
static String matrixFileName = "matrix.txt";
static int[][] matrix;
static int dimensions = 0;
public static void main(String[] args) {
matrix = analyzeFile();
bft();
}
static void bft(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter the source vertex, 0 to " + (matrix.length-1) + ".");
int source = input.nextInt()+1;
//Testing for valid vertex
while (source > matrix.length) {
System.out.println("Invalid vertex, please enter another from 0 to " + (matrix.length-1) + ".");
source = input.nextInt()+1;
}
input.close();
boolean[] visited = new boolean[matrix.length];
visited[source - 1] = true;
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
int height = 0;
System.out.println("The breadth first order is: ");
while(!queue.isEmpty()){
System.out.print(queue.peek()-1 + " ---> H");
int x = queue.poll();
int i;
for(i = 0 ; i < matrix.length; i++){
if(matrix[x-1][i] == 1 && visited[i] == false){
queue.add(i+1);
visited[i] = true;
height++;
}
}
System.out.print(height + "\n");
}
}
我正在寻找这样的输出格式
Please enter the source vertex, 0 to 7.
0
The breadth first order is:
0 ---> H5
1 ---> H6
2 ---> H6
3 ---> H6
4 ---> H7
5 ---> H7
6 ---> H7
7 ---> H7
我确定我只是错过了一些愚蠢的东西,但我不知所措。我需要跟踪访问的每个顶点的深度。邻接矩阵已成功从 .txt 文件中读取,并且在我的其他方法中运行良好。我可以是任何大小的简单,也可以不是。
任何意见表示赞赏,谢谢。
如果需要更多信息,请告诉我。
解决方案
使用 N 个整数创建数组“深度”,其中 N 是节点数并将其传递给 BFS
在 BFS 中,假设您将顶点“u”出列,您会发现它的邻居,并且对于“u”的每个新发现的邻居“v”,你设置depth[v]=depth[u] + 1
:
if(matrix[x-1][i] == 1 && visited[i] == false){
queue.add(i+1);
visited[i] = true;
depth[i] = depth[x]+1;
}
推荐阅读
- amazon-web-services - 云铸造 API [ 组织和空间 ]
- c# - SQL 实体框架通过包含列选项的继承建立索引
- postgresql - Postgres pgAdmin 一次重命名多个列
- python - 在列表列表中查找重叠列表
- docker - 重新创建修改后的 Docker 映像
- javascript - 为什么我会收到一条错误消息,指出 onAuth 不是函数?
- python - 将 str 日期(来自数据库)与 QDateTimeEdit 值进行比较
- java - 在比较器中使用变量
传递给 PriorityQueue - ruby - 如何让我的 cli 应用程序继续使用下一个方法?
- google-chrome - 无法在 initializeCastApi 读取未定义的属性“SessionRequest”