Dsa
Graphs Dfs
Hard
Forest Path Finder
Given a grid representing a forest where '1' represents trees and '0' represents open paths, find the longest path from the top-left corner (0,0) to the bottom-right corner (n-1,m-1) without stepping on any trees. You can only move right, down, left, or up. If there's no valid path, return -1.
Input:
- First line contains two integers n, m (1 <= n, m <= 100).
- Next n lines, each containing m integers (0 or 1), representing the grid.
Output:
- A single integer representing the length of the longest path found or -1 if no path exists.
Example:
Input:
3 3
0 0 0
1 1 0
0 0 0
Output:
6
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