Dsa
Graphs Dfs
Easy
Path Existence in a Graph
Write a program to determine whether there exists a path between two nodes in an undirected graph. The graph is defined by its number of nodes and a list of edges. The program must output 'YES' if a path exists and 'NO' otherwise.
Input format:
- The first line contains two integers, n (1 ≤ n ≤ 1000) and m (0 ≤ m ≤ 10,000).
- The second line contains two integers a and b, the start and end nodes.
- The next m lines contain the edges as two integers u and v.
Output format:
- 'YES' if a path exists from a to b, 'NO' otherwise.
Example:
Input:
5 4
1 5
1 2
2 3
3 4
4 1
Output:
YES
Key concepts
graphsdfspathfinding
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now