Nearest Bomb in Grid

TCS NQT Coding Easy Go Ad-Free - ₹20/mo

Given a 2D grid of size N x N where each cell contains either 0 (empty) or 1 (bomb), and a starting coordinate (startX, startY), find the Manhattan distance to the nearest bomb from the starting position. If no bomb exists, return -1.

Examples:

Input: grid = [[0,0,0],[0,1,0],[0,0,0]], start = (0,0)

Output: 2

Explanation: The bomb at (1,1) is nearest with Manhattan distance |0-1| + |0-1| = 2.

Input: grid = [[1,0],[0,0]], start = (1,1)

Output: 2

Input: grid = [[0,0],[0,0]], start = (0,0)

Output: -1

Constraints

  • 1 ≤ N < 1000
  • 0 ≤ startX, startY < N
  • grid[i][j] ∈ {0,1}