请求将TXT图结构输入转换为邻接表格式并补全无子节点项
Convert TXT Graph Input to Adjacency List in JavaScript & Cycle Detection Reference
Problem Overview
I need to convert graph structure input from a TXT file into a specified adjacency list format. The rules are as follows:
- First line values: Two numbers A and B where:
- A: Total number of unique numbered nodes in the file
- B: Total number of connections between nodes (e.g., pairs like 1-0, 0-1 count as separate connections)
- Remaining lines: Each line represents a direct connection between two nodes.
Expected Conversion Examples
Example 1 (No Outgoing Edges for Some Nodes)
Input:
3 2 0 1 1 2
Output:
{ 0 : [1], 1 : [2], 2 : [], }
Note: Nodes with no outgoing connections must have an empty array [] as their value.
Example 2 (Cyclic Graph)
Input:
2 2 1 0 0 1
Output:
{ 1 : [0], 0 : [1], }
Current JavaScript Code Issue
My existing JavaScript code can't complete the conversion properly, and it doesn't add empty arrays for nodes with no outgoing connections:
const USER_INPUT = "2 2\n1 0\n0 1"; function getInputLines(input) { const LINE_SEPARATOR = '\n'; return input.split(LINE_SEPARATOR); } function getLineElements(line) { const ELEM_SEPARATOR = ' '; return line.split(ELEM_SEPARATOR) }
Reference Python Code for Cycle Detection
Below is a Python snippet to detect cycles in a graph, provided for reference:
def cycle_exists(G): color = { u : "white" for u in G } found_cycle = [False] for u in G: if color[u] == "white": dfs_visit(G, u, color, found_cycle) if found_cycle[0]: break return found_cycle[0] def dfs_visit(G, u, color, found_cycle): if found_cycle[0]: return color[u] = "gray" for v in G[u]: if color[v] == "gray": found_cycle[0] = True return if color[v] == "white": dfs_visit(G, v, color, found_cycle) color[u] = "black"
Code Input Example:
graph = { 1 : [0], 0 : [] }
Call Example:
>>> cycle_exists(graph) >>> False
Content of this question originates from Stack Exchange, asked by user piotrek_k
相关产品推荐
相关产品推荐

