javascript - How should I find cycle in the directed graph and list out the nodes which are forming the cycle? - Stack Overflow

I have the array of objects in javascript i am trying to draw the directed graph how should i find whet

I have the array of objects in javascript i am trying to draw the directed graph how should i find whether it contains cycle or not if contains what are the elements forming the cycle Graph is not strongly connected and nodes can be isolated like "f"

 array = {};
//operations   parents
    array[a] = [b,c]
    array[b] = [d,c]
    array[e] = [a,b]
    array[d] = [e]
    array[f] = []

I want to find the cycle between the operations like here we have cycle from e-d-b-e? How should i find the cycle? I am using javascript.

I have the array of objects in javascript i am trying to draw the directed graph how should i find whether it contains cycle or not if contains what are the elements forming the cycle Graph is not strongly connected and nodes can be isolated like "f"

 array = {};
//operations   parents
    array[a] = [b,c]
    array[b] = [d,c]
    array[e] = [a,b]
    array[d] = [e]
    array[f] = []

I want to find the cycle between the operations like here we have cycle from e-d-b-e? How should i find the cycle? I am using javascript.

Share Improve this question edited Dec 28, 2021 at 4:45 Ahmed Nawaz Khan 1,8164 gold badges26 silver badges44 bronze badges asked Aug 16, 2017 at 14:37 Ayush RawatAyush Rawat 632 silver badges10 bronze badges 8
  • if you run a dfs on this graph and if you reach at the same node from where you started at some point, congrats you have found a cycle in any graph :p – zenwraight Commented Aug 16, 2017 at 14:44
  • What are the a, b, c, ... variables in your script, and is that all you have? – trincot Commented Aug 16, 2017 at 14:48
  • a,b,c are not variables they are the values these are a javascript object as (key,Values) – Ayush Rawat Commented Aug 16, 2017 at 14:50
  • If they are not variables, then that is not valid JavaScript. Valid literal values are numbers, strings (they must be quoted), booleans, null or undefined. a is none of those. – trincot Commented Aug 16, 2017 at 14:56
  • @trincot that's why I have assumed some values for a,b,c,d,e to show how the algorithm would basically work .... – zenwraight Commented Aug 16, 2017 at 15:15
 |  Show 3 more ments

4 Answers 4

Reset to default 5

Here is a BFS solution that will find one cycle (if there are any), which will be (one of) the shortest one(s).

function getCycle(graph) {
    // Copy the graph, converting all node references to String
    graph = Object.assign(...Object.keys(graph).map( node =>
                ({ [node]: graph[node].map(String) }) 
    ));

    let queue = Object.keys(graph).map( node => [node] );
    while (queue.length) {
        const batch = [];
        for (const path of queue) {
            const parents = graph[path[0]] || [];
            for (const node of parents) {
                if (node === path[path.length-1]) return [node, ...path];
                batch.push([node, ...path]);
            }
        }
        queue = batch;
    }
}

// First example
var graph = {
    a: ['b', 'c'],
    b: ['d', 'c'],
    e: ['a', 'b'],
    d: ['e']
};
var result = getCycle(graph);
console.log(result);

// Second example (numeric node references)
var graph = {
    0: [4],
    1: [4,0],
    2: [0,1],
    3: [1],
    4: [3]
};
var result = getCycle(graph);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

NB: If you define your graph with number references, a type conversion is needed since object properties are always of type string. We could use == instead of ===, but then the output will still be a mix of string and numbers; I think it is nicer to first convert every node reference to string.

Depth-First Search. If DFS finds an edge that points to an already discovered ancestor of the current node, the graph contains a cycle.

After referring to the ments on @zenwraigts solution I infer that this is a problem of Strongly Connected Components. You can find a good tutorial here, you can find javascript implementations here and here.

How is this a problem of SCC ?

all vertices which form a strongly connected ponent for a cycle, the problem reduces to finding all SCC's and print them

So as I mented, you need to basically traverse through the whole graph and keep a visited array to keep track of nodes that you have visited till now and if you reach any already visited node, then there exists a cycle in the provided directed graph.

To make your work easier here is a running code, you can use it as reference to build your algorithm on it.

Improved my answer little bit, iterating through all nodes, so that it covers some unreachable paths as well. Thank you all :)

array = {};

/*
Assuming 
a = 0
b=  1
c = 2
d = 3
e = 4
*/

// Here I am forming an adjacency list of directed nodes based on the diagram
array[0] = [4];
array[1] = [4,0];
array[2] = [0,1];
array[4] = [3];
array[3] = [1];
visited = {};
visited[0] = 0;
visited[1] = 0;
visited[2] = 0;
visited[3] = 0;
visited[4] = 0;

list_for_cycle_nodes = [];

for(var node = 0; node<5; node++) {
   if (dfs(node)) {
    for (var index = 0; index < list_for_cycle_nodes.length; index++) {
      console.log(list_for_cycle_nodes[index]+" ");
    }
    console.log('There is a cycle');
  } else {
    console.log('Yipee, there is no cycle');
  } 
}

function dfs(s) {
  if(visited[s] == 1) {
    return true;
  }
  list_for_cycle_nodes.push(s);
  visited[s] = 1;
  var flag = false;
  if(array[s].length <= 0) {
    return false;
  }
  for(var index = 0; index<array[s].length; index++) {
    flag = flag | dfs(array[s][index]);
    if(flag) {
      return true;
    }
  }
  return flag;
}

Hope this helps!

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745642480a4637776.html

相关推荐

  • 鸿蒙NEXT版仿华为阅读App的逐页浏览PDF

    上一篇文章虽然使用PdfView组件及其控制器实现了PDF文档的加载功能,但实际的渲染结果会把PDF的所有页面都显示出来,而非由用户控制的一页一页浏览。那么若想实现更加精细的浏览操作,就要引入PDF服务模块pdfService了。pdfSe

    2小时前
    20
  • JetBrains IDEs GO AI:最新coding agent,更智能的编程助手!

    大家好,欢迎来到程序视点!我是你们的老朋友.小二!JetBrains AI现在,AI 几乎无处不在。作为一名资深码农,我一直期待着有更智能、更高效的工具来提高开发的工作效率,并为开发带来更多乐趣,从而让自己从枯燥的CRUD中解放出来!从 2

    1小时前
    10
  • 我把AI接上了Figma、WhatsApp、浏览器……然后它开始自己动起来了!

    大家好,你有没有幻想过这样一幕:你家的 AI 助手,突然接过你的手机,自己发了条微信。 紧接着,它点开了 Chrome,滑动了几下网页,做了个表单提交。然后它打开了 Figma,开始画 UI 界面。 最后,它还用自己的声音给人打了个电话,说

    1小时前
    00
  • 三代测序技术100问(2):PacBio 与 ONT,谁是你的长读长利器?

    在上一期(三代测序技术100问(1):NGS与第三代测序,如何做出明智选择?)中,我们厘清了二代与三代测序技术的适用边界,明确了选择需“因题施策”。然而,踏入三代测序的大门,新的抉择又摆在面前:目前市场上主流的长读长技术平台主要由两大阵营引

    1小时前
    00
  • 鸿门宴讲PostgreSQL

    最近有点忙,被一个老师联系,说周日紧急救场。说是有一个大央企要做一节PostgreSQL的课,PPT都写好了,就让我去讲一讲就可以了。我这人好面子,紧急救场去吧,也没想太多。从此有意思的故事就开始了,因为要伪装成这家委托我企业的员工,资深的

    1小时前
    00
  • OFC 2025三菱报告:高速EML的结构设计和封装优化

    一、AI集群发展催生光互连技术需求从市场趋势来看,AI集群对光收发器的需求呈现出强劲的增长态势。AI Scale out网络中光收发器数量持续攀升,同时,预计从2028年起,AI Scale up市场也将迎来爆发 ,这使得光收发器的需求

    1小时前
    00
  • RAG 作者:RAG 已死,RAG 万岁!

    Datawhale分享 作者:Douwe Kiela,编译:思考机器本文作者 Douwe Kiela,RAG 论文(Retrieval-Augmented Generation for Knowledge-Intensive NLP Ta

    1小时前
    00
  • 设计模式:原型模式(Prototype)(1)

    又称克隆模式(Clone)。在 VFP 中,大多数基类都有一个 CloneObject 方法。但是很可惜,它只能在开发环境下使用。因此,可能只有开发过 IDE 工具的开发者才可能对其有兴趣。原型模式却可以在运行环境中克隆类实例。在现代OOP

    1小时前
    00
  • WIFI越近信号越强?CST电磁仿真看看

    在数字化浪潮席卷的现代社会,WiFi 早已深度融入日常生活与工作场景,成为不可或缺的关键要素。凭借便捷连接、高速传输的显著优势,WiFi 不仅重塑了人们的生活模式,还极大提升了工作效率。如今,无论是繁忙的办公室、温馨的餐厅,还是疾驰的交通工

    1小时前
    00
  • 告别复杂配置!中大型园区网络自动化开通流程实战解析

    到2025年,80%应用上云、30%流量为视频数据,传统网络无法支撑低时延、高可靠的云边协同需求。工业互联网场景中,TSN(时间敏感网络)等技术需网络架构深度重构以实现微秒级时延。传统园区网络的困境传统园区网络普遍存在部署周期长、管理复杂度

    1小时前
    00
  • 高效开发必备!小程序组件复用的实用技巧

    高效开发必备!支付宝小程序组件复用的实用技巧

    1小时前
    00
  • 业内首次! 全面复现DeepSeek

    机器之心发布机器之心编辑部OpenAI 的 o1 系列和 DeepSeek-R1 的成功充分证明,大规模强化学习已成为一种极为有效的方法,能够激发大型语言模型(LLM) 的复杂推理行为并显著提升其能力。然而,这些推理模型的核心训练方法在其技

    55分钟前
    00
  • 迈向长上下文视频生成!NUS团队新作FAR同时实现短视频和长视频预测SOTA,代码已开源

    本文由 NUS ShowLab 主导完成。第一作者顾宇超为新加坡国立大学 ShowLab@NUS 在读博士生,研究方向是视觉生成,在 CVPR、ICCV、NeurIPS 等国际顶级会议与期刊上发表多篇研究成果。第二作者毛维嘉为新加坡国立大学

    49分钟前
    00
  • 基于推理模型+RAG+Agent,作业帮内部安全体系建设实践

    文作业帮基础架构团队(吕亚霖、尚义龙) 背 景 在互联网智能化与 AI 大模型技术的双重驱动下,信息安全领域正遭遇史无前例的复杂挑战。从外部环境来看,AI 大模型的应用降低了攻击门槛。外部攻击者利用 AI 工具生成自动化攻击脚本、绕过

    46分钟前
    00
  • 从0到精通,System.Text.Json进阶技巧曝光,性能提升3倍!

    一、引言在现代软件开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,被广泛应用于前后端交互、配置文件管理以及分布式系统间的数据传输。System.Text.Json 是 .NET Core

    33分钟前
    00
  • 华为将大规模推出AI芯片,助力替代英伟达H100,打破限制!

    据路透社昨日凌晨独家报道,华为预计最早将在5月份推出大量910C AI芯片,部分产品已经开始出货。此次华为发布的新产品主要是为了应对美国对国内AI芯片的限制,助力国内企业缓解AI芯片供应紧张的问题。值得注意的是,本月美国政府要求英伟达销售H

    26分钟前
    00
  • 15分钟快速了解 Odoo

    一、引言在企业数字化转型进程中,开源 ERP 系统 Odoo 因模块化设计灵活、功能扩展性强而备受青睐。但新用户在安装和体验 Odoo 时会遭遇难题,像基于 Docker 技术的传统部署,步骤繁琐、镜像拉取不易、配置复杂且管理不便,令许多人

    19分钟前
    00
  • UML 2.0中的14种图简介

    UML(统一建模语言)2.0中定义了14种不同类型的图表,用于从不同角度描述系统。这些图表分为结构图和行为图两大类。可使用 PlantUML 绘制 UML 中的各种类型的图表: PlantUML是一个通用性很强的工具,可以快速、直接地创建

    17分钟前
    00
  • 如何搭建一个高效安全的API开放平台:完整步骤指南

    在当今数字化时代,API(应用程序编程接口)已成为连接不同系统和服务的桥梁。一个设计良好的API开放平台能够为企业带来巨大的商业价值和技术优势。本文将详细介绍从零开始搭建一个API开放平台的完整步骤,涵盖技术选型、架构设计、安全防护和运维管

    12分钟前
    00
  • UNEXPECTED

    参考资料使用VMware安装Windows系统‌Media Creation Tool制作启动盘大白菜启动盘制作失败怎么办?大白菜纯净版启动盘制作教程(2025版)UltraISO 软碟通Windows系统启动速度如何设置屏幕分辨率使用微软

    4分钟前
    00

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信