java - DFS(深度优先搜索)节点序列
问题描述
long
我想为Java类型的节点实现 dfs 。
我的算法正确计算了节点的数量和数量
边的数量,但不是节点的序列。请你帮助我好吗
修改我的算法,以便我计算节点的顺序
访问过,对吗?
这是我的代码:
private int getNumberOfNodes(long firstNode) {
List<Long> marked = new ArrayList<>(); //------------------------------------------->
Stack<Long> stack = new Stack<Long>(); //step 1 Create/declare stack
stack.push(firstNode); //Step 2 Put/push inside the first node
while (!stack.isEmpty()) { //Repeat till stack is empty:
Long node = stack.pop(); //Step 3 Extract the top node in the stack
marked.add(node); //------------------------------------------->
long[] neighbors = xgraph.getNeighborsOf(node); //Get neighbors
if (neighbors.length % 2 == 0) {
} else {
numOfNodesWithOddDegree++;
}
int mnt = 0;
for (long currentNode : neighbors) {
if (!marked.contains(currentNode) && !stack.contains(currentNode) ) { //&& !stack.contains(currentNode)
stack.push(currentNode);
} else {
}
if (!marked.contains(currentNode)) {
numOfEdges++;
}
}
}
return marked.size(); //(int) Arrays.stream(neighbors).count();
}
解决方案
我猜你检查marked
了序列的列表。
由于您的图是无向的,遍历的顺序可能会根据您首先推入堆栈的邻居而有所不同。这意味着您的功能的逻辑:
xgraph.getNeighborsOf(node)
可能会影响您的顺序。请参阅此 wiki 的顶点排序https://en.wikipedia.org/wiki/Depth-first_search
所以我的结论是:你可能有不同的遍历顺序,这并不意味着你的DFS是错误的,只要是Deep first search,与给定的答案稍有不同是可以的。
推荐阅读
- javascript - 如何单击一个点并将其坐标保存在 Leaflet 中?
- azure - Azure 数据工厂 - 休息复制活动附加标头不起作用
- google-cloud-platform - Terraform GCP - 参数在 windows-startup-script-ps1 中传递
- c# - 如何在 ScheduledTask 继承中实现依赖关系 (Telerik Sitefinity)
- kotlin - Mockito 如何测试在方法内创建的实例是否正在调用方法
- javascript - Javascript 代码在 JsFiddle 上工作,但在我的主机上不工作
- ruby-on-rails - 使用 Rails 6.1 应用程序在 Circle CI 上获得“未找到示例”
- python - TD Amertirade API 价格历史 - json 字符串返回
- android - Android - 从原生 android 应用程序调用 whatsapp 业务短链接时出现错误“QR 码不再有效”(仅在某些设备上)
- mongodb - 为什么 MongoDB 中的 Oplog 需要将多个更新转换为单个操作以保持幂等性?