Untying the knot

Let's talk about untying the knot...


You're given a fully-connected, undirected graph that contains at most one knot. A knot is defined as a loop. The graph contains only unique positive integers as the edges, and if an edge (a,b) is in the graph, then it is guaranteed that a!=b. The graph may have up to 10^5 nodes.
In order to untie the knot, you need to first find the loop (if it exists) in the graph, and then find the smallest element in that loop. In the example below, the graph does have one loop, and the smallest element (the weak link) is node 3. That's what you should return. Otherwise, if there is no loop, return -1.


Here is how I solved it:
1/ Created the graph (from the edges) using a hash table (that's my favorite way to handle a graph)
2/ Perform a DFS recursively looking for a loop
3/ As you do the DFS, store the current node and the parent node
4/ Once you find a loop, then backtrack non-recursively in order to find the smallest element
5/ Notice that because the graph is fully connected and undirected, you can start with any node whatsoever, but you also need to ensure that you don't repeat edges in your traversal

Code is down below, cheers, ACC.

using System;
using System.Collections;
using System.Collections.Generic;
namespace UntyingTheKnot
{
 public class NodePath
 {
 public int node = 0;
 public NodePath parent = null;
 public NodePath(int node, NodePath parent)
 {
 this.node = node;
 this.parent = parent;
 }
 }
 class Program
 {
 static void Main(string[] args)
 {
 int[][] edges1 = { new int[] { 1, 2 },
 new int[] { 2, 30 },
 new int[] { 30, 4 },
 new int[] { 30, 5 },
 new int[] { 5, 60 },
 new int[] { 5, 8 },
 new int[] { 8, 14 },
 new int[] { 14, 3 },
 new int[] { 3, 6 },
 new int[] { 6, 9 },
 new int[] { 8, 7 },
 new int[] { 9, 8 },
 new int[] { 9, 10 },
 new int[] { 10, 22 },
 new int[] { 10, 13 },
 new int[] { 13, 11 },
 new int[] { 13, 0 }
 };
 Console.WriteLine(UntieTheKnot(edges1));
 int[][] edges2 = { new int[] { 1, 2 },
 new int[] { 2, 3 },
 new int[] { 3, 1 }
 };
 Console.WriteLine(UntieTheKnot(edges2));
 int[][] edges3 = { new int[] { 1, 2 },
 new int[] { 2, 3 },
 new int[] { 3, 4 }
 };
 Console.WriteLine(UntieTheKnot(edges3));
 }
 static int UntieTheKnot(int[][] edges)
 {
 //Build the graph (hash table)
 Hashtable graph = new Hashtable();
 foreach (int[] edge in edges)
 {
 for (int i = 0; i < 2; i++)
 {
 if (!graph.ContainsKey(edge[i])) graph.Add(edge[i], new Hashtable());
 Hashtable connection = (Hashtable)graph[edge[i]];
 if (!connection.ContainsKey(edge[(i + 1) % 2])) connection.Add(edge[(i + 1) % 2], true);
 }
 }
 //We'll pick any node to begin with
 //Perform a DFS marking both the node and the edge (BFS does not work!)
 //The moment you find a cycle, find the min using backtrack
 int retVal = -1;
 Stack stack = new Stack();
 Hashtable visitedNode = new Hashtable();
 Hashtable visitedEdge = new Hashtable();
 NodePath nodePath = new NodePath(edges[0][0], null);
 UntieTheKnot_Recursive(nodePath,
 graph,
 visitedNode,
 visitedEdge,
 ref retVal);
 return retVal;
 }
 static bool UntieTheKnot_Recursive(NodePath currentNode,
 Hashtable graph,
 Hashtable visitedNode,
 Hashtable visitedEdge,
 ref int minVal)
 {
 if (currentNode == null) return false;
 if (visitedNode.ContainsKey(currentNode.node))
 {
 //Find min in the cycle
 int endNode = currentNode.node;
 Console.WriteLine("Node in knot: {0}", endNode);
 NodePath currentNodePath = currentNode.parent;
 minVal = Math.Min(currentNodePath.node, endNode);
 while (currentNodePath.node != endNode)
 {
 Console.WriteLine("Node in knot: {0}", currentNodePath.node);
 currentNodePath = currentNodePath.parent;
 minVal = Math.Min(currentNodePath.node, minVal);
 }
 return true;
 }
 visitedNode.Add(currentNode.node, true);
 if (graph.ContainsKey(currentNode.node))
 {
 Hashtable connections = (Hashtable)graph[currentNode.node];
 foreach (int connectedNode in connections.Keys)
 {
 long edgeHash = EdgeUniqueHash(currentNode.node, connectedNode);
 if (!visitedEdge.ContainsKey(edgeHash))
 {
 visitedEdge.Add(edgeHash, true);
 NodePath newNodePath = new NodePath(connectedNode, currentNode);
 if (UntieTheKnot_Recursive(newNodePath,
 graph,
 visitedNode,
 visitedEdge,
 ref minVal)) return true;
 }
 }
 }
 return false;
 }
 static long EdgeUniqueHash(int a, int b)
 {
 long min = Math.Min(a, b);
 long max = Math.Max(a, b);
 return min * 10005 + max;
 }
 }
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...