Given N cities which are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.
The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are blocked which means that water cannot pass through that particular city. Determine the maximum number of cities to which water can be supplied.
- The first line contains an integer >strong>N denoting the number of cities.
- The next N-1 lines contain two space-separated integers u v denoting a road between
city u and v.
- The next line contains N space-separated integers where it is 1 if the ith city is
blocked, else it is 0.
0 1 1 0
Explanation : If city 1 is chosen, then water is supplied from
city 1 to 2. If city 4 is chosen, water is supplied from city 4 to 3
hence maximum of 2 cities can be supplied with water.
0 1 1 0 0 0 0
Explanation : If city 1 is chosen than water is supplied from
city 1 to 2 or if city 4 is chosen water is supplied from city 4 to
3, 5, 6 and 7 hence maximum of 5 cities are supplied with water.
In this post a BFS based solution is discussed.
We run a breadth-first search on each city and check for two things: The city is not blocked and the city is not visited. If both these conditions return true then we run a breadth-first search from that city and count the number of cities up to which water can be supplied.
This solution can also be achieved using a depth-first search.
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Breadth First Search without using Queue
- Breadth First Search or BFS for a Graph
- Water Jug problem using BFS
- Water Connection Problem
- Applications of Breadth First Traversal
- Minimum number of Water to Land conversion to make two islands connected in a Grid
- Implementing Generic Graph in Java
- Best First Search (Informed Search)
- Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
- Bidirectional Search
- 2-Satisfiability (2-SAT) Problem
- Applications of Depth First Search
- Depth First Search or DFS for a Graph
- Level Ancestor Problem
- Channel Assignment Problem
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.
Improved By : bgangwar59