Given a tree with N nodes. Two players A and B start from node 1 and node N respectively. A can visit all the adjacent nodes to the nodes already visited by A but can not visit any nodes which is already visited by B and similarly for B also.
The player who visits more cities win. Find the player who wins if they both play optimally.
Input: Output: A wins
Approach: The optimal solution is that both the Player starts visiting the nodes which lie in the path connecting node 1 and node N. This is because one player cannot visit the nodes already visited by another player so each player will try to limit the number of nodes that can be visited by another player. Then it will be easy to count the number of nodes that can be visited by each player and find out the winner.
The DFS will be use to find out the path between two nodes and mark them one by one like 1 or 2, 1 for A and 2 for B and then mark all the adjacent unvisited nodes with the respective value and then calculate the count of nodes of A and B.
Below is the implementation of the above approach:
- Print levels with odd number of nodes and even number of nodes
- Check if two nodes are on same path in a tree
- Check whether the given node is in the path between the nodes U and V
- Check if two nodes are in same subtree of the root node
- Check if two nodes are cousins in a Binary Tree | Set-2
- Check if two nodes in a Binary Tree are siblings
- Check if two nodes are cousins in a Binary Tree
- Check sum of Covered and Uncovered nodes of Binary Tree
- Queries to check if the path between two nodes in a tree is a palindrome
- Given a n-ary tree, count number of nodes which have more number of children than parents
- Check if given path between two nodes of a graph represents a shortest paths
- Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
- Number of sink nodes in a graph
- Print all the levels with odd and even number of nodes in it | Set-2
- Number of nodes greater than a given value in n-ary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.