Dsa
Graphs Bfs
Easy
Treasure Island
You are exploring an island represented as a grid, where each cell has a type: land (0) or water (1). Your goal is to find the minimum number of steps to reach any treasure which is represented as a 2 in the grid. You can move to adjacent cells in four directions (up, down, left, right). If there is no reachable treasure, return -1.
Input format:
The first line contains an integer n (the size of the n x n grid).
The next n lines each contain n integers (0, 1, or 2) representing the grid layout.
Output format:
Print the minimum number of steps to reach a treasure or -1 if no treasure is reachable.
Example:
Input:
4
0 0 1 0
1 0 0 0
0 1 2 0
0 0 0 0
Output:
4
Key concepts
graphsbfsexploration
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