![]() |
VOOZH | about |
Given an undirected graph, your task is to choose a direction for each edge so that in the resulting directed graph's each node has an even outdegree. The outdegree of a node is the number of edges coming out of that node.
Examples:
Input: N = 4, M = 4, Edges = {{1, 3}, {3, 2}, {3, 4}, {1, 4}}
Output:
3 1
3 2
4 3
4 1
Explanation: Each node in the resulting directed graph has an even outdegree: node 1 has outdegree 0, node 2 has outdegree 0, node 3 has outdegree 0, and node 4 has outdegree 2.Input: N = 3, M = 2, Edges = {{1, 3}, {3, 2}}
Output:
3 1
3 2
Explanation: Each node in the resulting directed graph has an even outdegree: node 1 has outdegree 0, node 2 has outdegree 2, node 3 has outdegree 0.
Approach: To solve the problem, follow the below idea:
The problem can be solved using Depth-First Search. We use an even array to keep track of nodes with even outdegrees during the traversal. If a node has an even outdegree, the edge is directed from the parent to the child. otherwise, the edge is directed from the child to the parent. This process continues until all nodes are visited. After the traversal, the algorithm checks if all nodes have an even outdegree. If they do, it prints the directed edges. otherwise, it prints "IMPOSSIBLE."
3 1 3 2 4 3 4 1
Time Complexity: O(V+E), where V is the number of nodes and E is the number of edges
Auxiliary Space: O(V+E) due to the storage required for the adjacency list and other arrays.