• 0

[C++] How to check if a graph is in a cycle


Question

Basically I am trying to check if a graph is in a cycle. It might be a little hard to explain but in the pics I have below you can see P1, P2, P3. There are arrows from one to others. If one array leads to one and to another and back to itself then its in a cycle. The graph below is not in a cycle. I have stored the information such that the P's correspond to the indexes of the array and the linked lists tell where that P is pointing to. P1 is pointing to both P2 and P3 therefore the array's index is 1 for P1 and with links of 2 and 3, meaning its arrows are pointing to P2 and P3. The problem is I am trying to find a simple and easy way to figure out how to find if there is a cycle. For example if P1 is pointing to P2 and P2 is pointing to P3 and P3 is pointing back to P1 that would be a cycle. Thanks for any help!!!!

post-47-1092177822.gif

Edited by saiz66

20 answers to this question

Recommended Posts

  • 0

First off, I don't think that an array of linked lists is the best way to do this. Though it's just my preference, I'd recommend setting up a 2d array as your adjacency matrix. Whenever using graphs, adjacency matrices tend to be the way to go. A recursive or iterative function(Your personal preference) will easily do the rest :D

  • 0

I thought of an idea.. but it would be very complicated.. well not that complicated but it would have many steps.. first trace the P1 of the first node it is pointing to in this case 2 and since index 2 is pointing to 3 go to index 3 and look up 1 and since we started from 1, that is P1 it is in a cycle.. even though I stated in my frist post that it wasnt in a cycle.. I guess I was wrong... this way seems to be the "hard" way of doing it.. i was just wondering if there was an easier way.

  • 0

degree means number of edges connected to a vertex.

as u have a more tree like structure, u may want to traverse the whole tree in a depth first or breadth first manner, keeping a history of all the nodes visited. If any are repeated, that means it has cycle (this method may become too extensive when trying to traverse large number or nodes)

  • 0

What you could do is do a recursive algorithm... something like this...

For your example above you should create linked list elements like this:

struct element {

int x;

element next;

};

where x contains the subscript (1, 2 3) and P.next would point to an element this P would connect to with an arrow

Then create a P object with x =1 (that would be P1), and do a recursive search:

element currNode = p;

do {

if (currNode.next == p)

{

// then the loop hits back to start, and is a cycle

cout << "Is a cycle";

break;

}

currNode = currNode.next;

} while (currNode != NULL)

// if the currNode == NULL then the end of the list is found and no cycle exists

Finally just extend this to have more than just one node per element... as in

struct element {

int x;

element next1;

element next2;

};

Hope that helps!

  • 0

I am using the lists from the library.

std::list<int> waitFor[Max];

I am not sure if you are familiar with this. I am not too good with c++ but it seems to me that your code only checks for if the node is an elment but what if look at my graph at the bottom... P1 points to P2 and P2 points to P3 and P4... so then I gotta check if P3 or P4 is pointing to P1... This is really confusing me... Could you explain how yours works? It seems much simpler than what I was thinking. Thanks by the way!

post-47-1092714022.gif

  • 0
  saiz66 said:
I am using the lists from the library. 

std::list<int> waitFor[Max];

I am not sure if you are familiar with this.  I am not too good with c++ but it seems to me that your code only checks for if the node is an elment but what if look at my graph at the bottom... P1 points to P2 and P2 points to P3 and P4... so then I gotta check if P3 or P4 is pointing to P1... This is really confusing me... Could you explain how yours works?  It seems much simpler than what I was thinking.  Thanks by the way!

I'm still confused on what you're trying to do. Your memory map of the lists show something completely different than your state diagram. What you need to do is go from your starting point and see if the destination is the same. This may mean going through multiple ways as each state can go to multiple states. It would be like dealing with a tree.

  • 0

To Kjordan:

I am not sure what you are confused by. Is it my diagram and the array of linked lists? The indexes are the Processes. So Process 1 is pointing to Process 2. So there is a linked list of 2 for Index 1. And Index 2 is process 2 which is pointing to 2 processes, 3 and 4 which are shown by the linked lists 3 and 4. And Index 3 has nothing so no linked lists for that. And Process 4 is pointing to 1 and 3 which are shown by the nodes 1 and 3.

To Blivrail:

I would use your method but I am using linked lists of arrays and I have incorporated that into my program so changing it would be difficult. If it is possible to use it with my setup then that would be great.

Basically this is my idea. I go through each node to check where it would be going and checkin if there is a cycle. So from my example graph. I would check Index 1 linked list 2 and then check all the indexes for 2 to see if it goes back to 1. Since none don't I would have to check each node, 3. Then go to 3 where there is nothing. Then I got to check Index 2 and check Index 4.

This is what I got so far:

void checkDeadlock(list&lt;int&gt;* waitFor)
{
	int i, tempIndex, tempNode, startIndex, startNode;

	for (i=0; i&lt;Max; i++)
	{
  
  list&lt;int&gt;::iterator it = waitFor[i].begin();
  
  while (it != waitFor[i].end())
  {

 	 tempIndex = i;
 	 tempNode = *it;

 	 while (it != waitFor[tempNode].end())
 	 {
    if (tempIndex == *it)
   	 cout &lt;&lt; "It is a cycle" &lt;&lt; endl;
    else 
   	 ++it;

 	 }

 	 // Increment the iterator to the next element
 	 ++it;
  }
	}

}

I know this is not complete. Anybody can help me out?

post-47-1092759058.gif

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • They've been focusing on security and quality? Could have fooled me. Their own paying customers literally just got breached because they failed to push SharePoint updates downstream to on prem servers operating outside of their "365" ecosystem.
    • The animosity is unnecessary, when I opened the page I only saw one response which never mentioned your other steps, and when I hit reply it jumped straight to the bottom and again, I saw no other responses.  I was simply agreeing with the first comment that said yes, you should be fine if you erase its current operating system. Using another PC, or the copy of Windows that comes on that PC (former option is more trustworthy), download and run the Windows Media Creation tool.  It will walk you thru the process of downloading Windows and writing it to a USB stick.  It will even ask you at one point whether you're reinstalling it to the current machine or installing it on another machine. Then just boot the PC in question from that USB stick.  Usually spamming Esc, Del, F-8, F-9, F-10, F-11, F-12 or F-2 immediately after power on will bring up a boot menu, it varies by manufacturer.  If Windows starts booting you either missed your window or hit the wrong key. Follow the on-screen instructions.  When it gets to the disk formatting part I usually just delete all the partitions on the destination drive, then select the unpartitioned space as my destination.  The Windows installer will then automatically partition the drive as needed. Be prepared to download drivers from the PC manufacturer's website, they may not come bundled with Windows and you may not be able to use things like WiFi or ethernet until you have them.  They "might" work straight away, but they also might not.  Better to be prepared with a spare PC and a USB stick to transfer them over.
    • Wise Disk Cleaner 11.2.5 by Razvan Serea Wise Disk Cleaner is a free disk utility designed to help you keep your disk clean by deleting any unnecessary files. Usually, these unnecessary, or junk files appear as a result of program's incomplete uninstalls, or Temporary Internet Files. It is best if these files are wiped out from time to time, since they may, at some point, use a considerable amount of space on your drives. Wise Disk Cleaner, with its intuitive and easy to use interface, helps you quickly wipe out all the junk files. Using the program is indeed easy. It also works fast when both scanning for files and deleting files. The new Wise Disk Cleaner has more advantages: improved performance, better interface and scans/cleans more thoroughly. Wise Disk Cleaner Free provides lifetime free update service and Unlimited Free technical support. The first Slimming System software Wise Disk Cleaner is the first system slimming tool, which will help you to remove Windows useless files that you don't need, such as Korean IME, Windows Sample music, videos, pictures, Installers and Uninstallers of Updates Patches etc. Wise Disk Cleaner 11.2.5 Build 845 changelog: Added cleaning rules for Legacy Games Launcher, Letasoft Sound Booster, Macrium Reflect, MagicLine4NX, MAGIX Photostory, MakeHuman, Max Recorder, Maxprog iCash, Lexware, LG PC Suite, Lightworks, LINE, Listary, and LockHunter. Improved cleaning rules for Xunlei, PowerToys, Meitu, OneDrive, and Tencent Video. For security reasons, users can no longer delete the latest system restore point in the Restore Center. Enhanced System Slimming. Fixed minor bugs from the previous version. Download: Wise Disk Cleaner 11.2.5 | 6.9 MB (Freeware) Download: Portable Wise Disk Cleaner 11.2.5 | 7.3 MB View: Wise Disk Cleaner Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • I keep getting ignored when I ask what you guys mean by nuke it. I described the steps and I keep getting the same generic instructions. Can you look at what I have posted multiple times already and validate what I have described? You can't assume everyone has your level of expertise and can interpret your nuking advice. After this many posts in this thread, I don't think we need the same generic advice about just nuke it and reinstall. It's already been said. So can you please outline the specifics? Made in Ukraine? Are you sure?
  • Recent Achievements

    • Week One Done
      Itbob513626 earned a badge
      Week One Done
    • One Month Later
      Itbob513626 earned a badge
      One Month Later
    • Rookie
      EdwardFranciscoVilla went up a rank
      Rookie
    • Week One Done
      MoJo624 earned a badge
      Week One Done
    • Collaborator
      aeganwn earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      618
    2. 2
      ATLien_0
      241
    3. 3
      Xenon
      157
    4. 4
      +FloatingFatMan
      122
    5. 5
      Michael Scrip
      121
  • Tell a friend

    Love Neowin? Tell a friend!