Connecting Tech Pros Worldwide Forums | Help | Site Map

Simple graph with one cycle brain teaser

RedSon's Avatar
Site Moderator
 
Join Date: Jan 2007
Location: America
Posts: 3,392
#1: May 8 '07
Given a directed graph of k-nodes such that the last node creates a cycle with any other node determine which node the last node's edge points to using the minimum amount of resources and without having the ability to change the data in the node.
Expand|Select|Wrap|Line Numbers
  1. Visual:
  2. O ---> O ---> O ---> ... ---> O --+
  3.               ^                   |
  4.               |                   |
  5.               +-------------------+
  6.  
  7.  
This is seriously not a homework question. You can't mark the node as "visited" and you are discouraged from using any other data structures like copies of the linked list or additional boolean arrays and what not. The best solution will use a minimum amount of memory. Solutions that are bounded by large big Ohs will be fine too.

I've been thinking about this all day. Its quite a brain teaser. How do you figure it out by using only a few pointers and maybe one or two temporary node variables?

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: May 15 '07

re: Simple graph with one cycle brain teaser


Expand|Select|Wrap|Line Numbers
  1. Node findCycle(Node current, int k, Node target) {
  2.    if (current == target) return current; // found a cycle?
  3.    if (k == 0) return null; // not allowed to probe any further?
  4.  
  5.    for (all outgoing edges from current) // probe k steps from this node
  6.       if (findCycle(next, k-1, current) != null)
  7.          return current;
  8.    // no cycle found; try further nodes:
  9.    for (all outgoing edges from current) 
  10.       if (findCycle(next, k, next) != null) // next node target of a cycle?
  11.          return next;
  12.    return null;
  13. }
The big-Oh is terrible: from every node k steps are done at most to find a cycle
where k is the number of nodes in the graph.

kind regards,

Jos
Motoma's Avatar
Moderator
 
Join Date: Jan 2007
Location: Maine, USA
Posts: 2,904
#3: May 25 '07

re: Simple graph with one cycle brain teaser


Traverse the graph backwards.
Reply