
Ranti A.
asked 10/05/20Give an algorithm to check whether a given undirected graph has cycles of odd length. The length of a cycle is the number of vertices (or equivalently, the number of edges) in the cycle.
Use Breadth First Search (BFS).
More
1 Expert Answer
Sid M. answered 01/01/21
Tutor
5.0
(657)
Studied Computer Science and Engineering at University of Washington
Not exactly an *expert* answer, but this is the first thing that comes to mind.
First, some things to keep in mind:
- As an *undirected* graph, any node B that node A can reach can also reach node A. This means that we have to remember that we've seen node A.
- BFS allows us to order the nodes of a graph into 'layers', wherein each layer is connected to the next by a single edge, so
- if we ensure that each node 'retained' in the BFS is unique, and
- we remember which level with (first) saw the node, then
- we can use the difference in 'layer' between the first and any other time we see a node to identify the number of edges of a span or cycle.
So:
- Create an empty map of node to cardinal, node-to-level, and an empty queue of nodes, next-nodes. (We'll use node-to-level to both keep track of whether we've seen a node already, and at what level we first saw it. We use next-nodes to implement BFS.)
- Push any node, n, from the graph onto next-nodes, and record its [current] level, node-to-level[current-node] = 0.
- While next-nodes is not empty, pop current-node from the queue:
- Set current-level = node-to-level[current-node].
- For each node, connected-node, reachable from current-node:
- If connected-node is already in node-to-level, then we have identified a cycle.
- The length of the cycle is length = current-level - node-to-level[connected-node].
- If length is odd, report it.
- Otherwise;
- remember connected-node's level, node-to-level[connected-node] = current-level + 1, and
- push connected-node onto next-nodes.
Still looking for help? Get the right answer, fast.
Ask a question for free
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Find an Online Tutor Now
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Isaac W.
the length of the cycle is the number of vertices - 1 , since you do not have to use every edge in a graph in order to reach each vertex, using a prim's minumum spanning tree you can find the shortest path to reach all vertecies which will always be the number of vertices in an unweighted graph.12/04/20