4600-project-2/src/knotted.cpp
2022-04-29 02:11:11 +00:00

48 lines
2.1 KiB
C++

/* +----------------+---------+--------------------------+
| Michael Laymon | mal0420 | MichaelLaymon@my.unt.edu |
+----------------+---------+--------------------------+
| Created 2022-04-17 | Updated 2022-04-28 |
+--------------------------+--------------------------+ */
#include <cstdlib>
#include <set> // why set? because it supports find and it makes it easier.
#include "graph.hpp"
// depth-first-search is needed to detect the knot in the graph
bool graph::DFS ( int node, std::set<int>&visited, int parent ) {
visited.insert(node); // once we come across this node, mark it as visited in the set
// note: node in this function is called using the iterator from the calling function.
for ( int ii = 0; ii < (num_processes+num_resources); ii++ ) { // for every process and resource...
if ( m[node][ii] ) { // m is the matrix part of graph class; if the valu
if ( ii == parent ) continue; // if index is parent, skip
if ( visited.find(ii) != visited.end() ) return true; // case index is visited, already visited
if ( DFS( ii, visited, node ) ) return true; // if search results is true
}//\if
}//\for
return false;
}
// this runs a DFS search on an undirected graph to detect a knot
bool graph::detectKnot() {
std::set<int> visited; // define a set to keep track of visited nodes; a cycle will revisit visited nodes
for ( int ii = 0; ii < (num_processes+num_resources); ii++ ) { // for every process and resource...
if ( visited.find(ii) != visited.end() ) continue; // if this node is already found in visited, skip
if ( DFS(ii,visited,-1) ) return true; // start DFS with -1 for parent node, then it continues recursively
continue; // if neither above is true, continue searching until DFS is complete
}//\for
return false; // if no knot is found, return false
}
/* knotted:
Perform the knot detection algorithm on the adjacency matrix to detect deadlocks
@params:
none, uses class-internal data
@returns:
bool:
true iff graph is knotted (deadlock)
false if graph is not knotted (no deadlock)
*/
bool graph::knotted() {
return (detectKnot()) ? true : false;
}