Spidey Sense

Last Updated : 1 Aug, 2026

Given an n × m grid mat[][] consisting of the characters 'O', 'B', and 'W', where 'O' represents an open cell, 'B' represents a bomb, and 'W' represents a wall. A move can be made from a cell to any of its four adjacent cells (up, down, left, and right), and walls cannot be crossed.

Replace each cell in the grid as follows:

  • Replace every 'B' with 0.
  • Replace every 'W' with -1.
  • Replace every 'O' with the minimum number of moves required to reach the nearest bomb without passing through any wall. If an open cell cannot reach any bomb, replace it with -1.

Return the resulting integer matrix.

Examples:

Input: mat[][] = [['O', 'O', 'O'], ['W', 'B', 'B'], ['W', 'O', 'O']]

311

Output: [[2, 1, 1], [-1, 0, 0], [-1, 1, 1]]
Explanation: The wall cells (1,0) and (2,0) are replaced with -1, and the bomb cells (1,1) and (1,2) are replaced with 0. Each open cell is assigned the minimum distance to the nearest bomb without crossing any wall. Thus, the open cells (0,0), (0,1), (0,2), (2,1), and (2,2) are replaced with 2, 1, 1, 1, and 1 respectively.

Input: mat[][] = [['O', 'O'], ['O', 'O']]

312

Output: [[-1, -1], [-1, -1]]
Explanation: There is no bomb in the grid, so none of the open cells can reach a bomb. Hence, all open cells are replaced with -1.

Try It Yourself
redirect icon

[Naive Approach] BFS for Every Open Cell - O((n * m) ^ 2) Time and O(n * m) Space

Since every move to an adjacent cell has the same cost (1 move), the problem is a shortest path problem in an unweighted grid. The idea here is to use BFS as the ideal choice because it explores cells level by level, ensuring that the first bomb reached is always the nearest one. Therefore, we perform a separate BFS from every open cell to compute its minimum distance to a bomb while treating walls as blocked cells.

  • Create an answer matrix and initialize all cells with -1.
  • Traverse the grid and set bombs ('B') to 0 and walls ('W') to -1.
  • For every open cell ('O'), perform a BFS starting from that cell.
  • During BFS, visit only valid and unvisited cells while skipping walls.
  • As soon as a bomb is reached, store the current BFS level as the minimum distance.
  • If the BFS finishes without reaching any bomb, keep the answer as -1.
C++
#include <bits/stdc++.h>
using namespace std;

// Performs BFS from the given open cell and
// returns the distance to the nearest bomb.
int bfs(int row, int col, vector<vector<char>> &mat)
{
    int n = mat.size();
    int m = mat[0].size();

    // Visited array for the current BFS
    vector<vector<bool>> visited(n, vector<bool>(m, false));

    queue<pair<int, int>> q;

    q.push({row, col});
    visited[row][col] = true;

    int distance = 0;

    while (!q.empty())
    {
        int size = q.size();

        while (size--)
        {
            auto curr = q.front();
            q.pop();

            int i = curr.first;
            int j = curr.second;

            // Bomb found
            if (mat[i][j] == 'B')
            {
                return distance;
            }

            // Move Down
            if (i + 1 < n && mat[i + 1][j] != 'W' && !visited[i + 1][j])
            {
                visited[i + 1][j] = true;
                q.push({i + 1, j});
            }

            // Move Up
            if (i - 1 >= 0 && mat[i - 1][j] != 'W' && !visited[i - 1][j])
            {
                visited[i - 1][j] = true;
                q.push({i - 1, j});
            }

            // Move Right
            if (j + 1 < m && mat[i][j + 1] != 'W' && !visited[i][j + 1])
            {
                visited[i][j + 1] = true;
                q.push({i, j + 1});
            }

            // Move Left
            if (j - 1 >= 0 && mat[i][j - 1] != 'W' && !visited[i][j - 1])
            {
                visited[i][j - 1] = true;
                q.push({i, j - 1});
            }
        }

        // Move to the next BFS level
        distance++;
    }

    // No bomb is reachable
    return -1;
}

vector<vector<int>> findDistance(vector<vector<char>> &mat)
{
    int n = mat.size();
    int m = mat[0].size();

    // Initialize the answer matrix with -1
    vector<vector<int>> ans(n, vector<int>(m, -1));

    // Process every cell in the grid
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {

            // Bomb cell
            if (mat[i][j] == 'B')
            {
                ans[i][j] = 0;
            }

            // Wall cell
            else if (mat[i][j] == 'W')
            {
                ans[i][j] = -1;
            }

            // Find the nearest bomb for every open cell
            else
            {
                ans[i][j] = bfs(i, j, mat);
            }
        }
    }

    return ans;
}

int main()
{
    vector<vector<char>> mat = {{'O', 'O', 'O'}, {'W', 'B', 'B'}, {'W', 'O', 'O'}};

    vector<vector<int>> ans = findDistance(mat);

    for (auto &row : ans)
    {
        for (auto &x : row)
        {
            cout << x << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
import java.util.*;

class GFG {

    // Performs BFS from the given open cell and
    // returns the distance to the nearest bomb.
    static int bfs(int row, int col, char[][] mat)
    {
        int n = mat.length;
        int m = mat[0].length;

        // Visited array for the current BFS
        boolean[][] visited = new boolean[n][m];

        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[] { row, col });
        visited[row][col] = true;

        int distance = 0;

        while (!q.isEmpty()) {

            int size = q.size();

            while (size-- > 0) {

                int[] curr = q.poll();
                int i = curr[0];
                int j = curr[1];

                // Bomb found
                if (mat[i][j] == 'B') {
                    return distance;
                }

                // Move Down
                if (i + 1 < n && mat[i + 1][j] != 'W'
                    && !visited[i + 1][j]) {
                    visited[i + 1][j] = true;
                    q.offer(new int[] { i + 1, j });
                }

                // Move Up
                if (i - 1 >= 0 && mat[i - 1][j] != 'W'
                    && !visited[i - 1][j]) {
                    visited[i - 1][j] = true;
                    q.offer(new int[] { i - 1, j });
                }

                // Move Right
                if (j + 1 < m && mat[i][j + 1] != 'W'
                    && !visited[i][j + 1]) {
                    visited[i][j + 1] = true;
                    q.offer(new int[] { i, j + 1 });
                }

                // Move Left
                if (j - 1 >= 0 && mat[i][j - 1] != 'W'
                    && !visited[i][j - 1]) {
                    visited[i][j - 1] = true;
                    q.offer(new int[] { i, j - 1 });
                }
            }

            // Move to the next BFS level
            distance++;
        }

        // No bomb is reachable
        return -1;
    }

    static ArrayList<ArrayList<Integer> >
    findDistance(char[][] mat)
    {
        int n = mat.length;
        int m = mat[0].length;

        // Initialize the answer matrix
        ArrayList<ArrayList<Integer> > ans
            = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            ans.add(new ArrayList<>());
            for (int j = 0; j < m; j++) {

                // Bomb cell
                if (mat[i][j] == 'B') {
                    ans.get(i).add(0);
                }

                // Wall cell
                else if (mat[i][j] == 'W') {
                    ans.get(i).add(-1);
                }

                // Find the nearest bomb for every open cell
                else {
                    ans.get(i).add(bfs(i, j, mat));
                }
            }
        }

        return ans;
    }

    public static void main(String[] args)
    {
        char[][] mat = { { 'O', 'O', 'O' },
                         { 'W', 'B', 'B' },
                         { 'W', 'O', 'O' } };

        ArrayList<ArrayList<Integer> > ans
            = findDistance(mat);

        for (ArrayList<Integer> row : ans) {
            for (int x : row)
                System.out.print(x + " ");
            System.out.println();
        }
    }
}
Python
from collections import deque

# Performs BFS from the given open cell and
# returns the distance to the nearest bomb.
def bfs(row, col, mat):

    n = len(mat)
    m = len(mat[0])

    # Visited array for the current BFS
    visited = [[False] * m for _ in range(n)]

    q = deque()
    q.append((row, col))
    visited[row][col] = True

    distance = 0

    while q:

        size = len(q)

        for _ in range(size):

            i, j = q.popleft()

            # Bomb found
            if mat[i][j] == 'B':
                return distance

            # Move Down
            if i + 1 < n and mat[i + 1][j] != 'W' and not visited[i + 1][j]:
                visited[i + 1][j] = True
                q.append((i + 1, j))

            # Move Up
            if i - 1 >= 0 and mat[i - 1][j] != 'W' and not visited[i - 1][j]:
                visited[i - 1][j] = True
                q.append((i - 1, j))

            # Move Right
            if j + 1 < m and mat[i][j + 1] != 'W' and not visited[i][j + 1]:
                visited[i][j + 1] = True
                q.append((i, j + 1))

            # Move Left
            if j - 1 >= 0 and mat[i][j - 1] != 'W' and not visited[i][j - 1]:
                visited[i][j - 1] = True
                q.append((i, j - 1))

        # Move to the next BFS level
        distance += 1

    # No bomb is reachable
    return -1


def findDistance(mat):

    n = len(mat)
    m = len(mat[0])

    # Initialize the answer matrix with -1
    ans = [[-1] * m for _ in range(n)]

    # Process every cell in the grid
    for i in range(n):
        for j in range(m):

            # Bomb cell
            if mat[i][j] == 'B':
                ans[i][j] = 0

            # Wall cell
            elif mat[i][j] == 'W':
                ans[i][j] = -1

            # Find the nearest bomb for every open cell
            else:
                ans[i][j] = bfs(i, j, mat)

    return ans

# Driver Code
if __name__ == "__main__":
    mat = [
        ['O', 'O', 'O'],
        ['W', 'B', 'B'],
        ['W', 'O', 'O']
    ]

    ans = findDistance(mat)

    for row in ans:
        print(*row)
C#
using System;
using System.Collections.Generic;

class GFG {
    
    // Performs BFS from the given open cell and
    // returns the distance to the nearest bomb.
    static int BFS(int row, int col, char[, ] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        // Visited array for the current BFS
        bool[, ] visited = new bool[n, m];

        Queue<(int, int)> q = new Queue<(int, int)>();
        q.Enqueue((row, col));
        visited[row, col] = true;

        int distance = 0;

        while (q.Count > 0) {
            int size = q.Count;

            while (size-- > 0) {
                var(i, j) = q.Dequeue();

                // Bomb found
                if (mat[i, j] == 'B')
                    return distance;

                // Move Down
                if (i + 1 < n && mat[i + 1, j] != 'W'
                    && !visited[i + 1, j]) {
                    visited[i + 1, j] = true;
                    q.Enqueue((i + 1, j));
                }

                // Move Up
                if (i - 1 >= 0 && mat[i - 1, j] != 'W'
                    && !visited[i - 1, j]) {
                    visited[i - 1, j] = true;
                    q.Enqueue((i - 1, j));
                }

                // Move Right
                if (j + 1 < m && mat[i, j + 1] != 'W'
                    && !visited[i, j + 1]) {
                    visited[i, j + 1] = true;
                    q.Enqueue((i, j + 1));
                }

                // Move Left
                if (j - 1 >= 0 && mat[i, j - 1] != 'W'
                    && !visited[i, j - 1]) {
                    visited[i, j - 1] = true;
                    q.Enqueue((i, j - 1));
                }
            }

            // Move to the next BFS level
            distance++;
        }

        // No bomb is reachable
        return -1;
    }

    static List<List<int> > findDistance(char[, ] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        // Initialize the answer matrix with -1
        List<List<int> > ans = new List<List<int> >();

        for (int i = 0; i < n; i++) {
            List<int> row = new List<int>();

            for (int j = 0; j < m; j++) {
                // Bomb cell
                if (mat[i, j] == 'B')
                    row.Add(0);

                // Wall cell
                else if (mat[i, j] == 'W')
                    row.Add(-1);

                // Find the nearest bomb for every open cell
                else
                    row.Add(BFS(i, j, mat));
            }

            ans.Add(row);
        }

        return ans;
    }

    static void Main()
    {
        char[, ] mat = { { 'O', 'O', 'O' },
                         { 'W', 'B', 'B' },
                         { 'W', 'O', 'O' } };

        List<List<int> > ans = findDistance(mat);

        foreach(var row in ans)
        {
            foreach(var x in row) Console.Write(x + " ");
            Console.WriteLine();
        }
    }
}
JavaScript
// Performs BFS from the given open cell and
// returns the distance to the nearest bomb.
function bfs(row, col, mat)
{
    const n = mat.length;
    const m = mat[0].length;

    // Visited array for the current BFS
    const visited = Array.from({length : n},
                               () => Array(m).fill(false));

    const q = [];
    let front = 0;

    q.push([ row, col ]);
    visited[row][col] = true;

    let distance = 0;

    while (front < q.length) {

        let size = q.length - front;

        while (size--) {

            const [i, j] = q[front++];

            // Bomb found
            if (mat[i][j] === "B")
                return distance;

            // Move Down
            if (i + 1 < n && mat[i + 1][j] !== "W"
                && !visited[i + 1][j]) {
                visited[i + 1][j] = true;
                q.push([ i + 1, j ]);
            }

            // Move Up
            if (i - 1 >= 0 && mat[i - 1][j] !== "W"
                && !visited[i - 1][j]) {
                visited[i - 1][j] = true;
                q.push([ i - 1, j ]);
            }

            // Move Right
            if (j + 1 < m && mat[i][j + 1] !== "W"
                && !visited[i][j + 1]) {
                visited[i][j + 1] = true;
                q.push([ i, j + 1 ]);
            }

            // Move Left
            if (j - 1 >= 0 && mat[i][j - 1] !== "W"
                && !visited[i][j - 1]) {
                visited[i][j - 1] = true;
                q.push([ i, j - 1 ]);
            }
        }

        // Move to the next BFS level
        distance++;
    }

    // No bomb is reachable
    return -1;
}

function findDistance(mat)
{
    const n = mat.length;
    const m = mat[0].length;

    // Initialize the answer matrix with -1
    const ans
        = Array.from({length : n}, () => Array(m).fill(-1));

    // Process every cell in the grid
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // Bomb cell
            if (mat[i][j] === "B")
                ans[i][j] = 0;

            // Wall cell
            else if (mat[i][j] === "W")
                ans[i][j] = -1;

            // Find the nearest bomb for every open cell
            else
                ans[i][j] = bfs(i, j, mat);
        }
    }

    return ans;
}

// Driver Code
const mat = [
    [ "O", "O", "O" ], [ "W", "B", "B" ], [ "W", "O", "O" ]
];

const ans = findDistance(mat);

for (const row of ans)
    console.log(row.join(" "));

Output
2 1 1 
-1 0 0 
-1 1 1 

[Expected Approach] Using Multi Source BFS - O(n * m) Time and O(n * m) Space

In the previous approach, we performed a separate BFS from every open cell to find its nearest bomb. This causes the same cells to be visited repeatedly, leading to unnecessary computations.

Instead of starting a BFS from every open cell, we can reverse our perspective and start the BFS from all bomb cells simultaneously. Since BFS explores cells level by level, the first time an open cell is reached, it is guaranteed to be from its nearest bomb.

  • Create the answer matrix and initialize all cells with -1.
  • Traverse the grid, set every bomb ('B') to 0, and insert all bomb cells into the BFS queue.
  • Perform a BFS starting simultaneously from all bomb cells.
  • For each popped cell, visit all valid adjacent open cells that have not been visited.
  • Assign each visited open cell a distance of current distance + 1 and push it into the queue.
  • After the BFS finishes, unreachable open cells remain -1, while walls also remain -1.
C++
#include <bits/stdc++.h>
using namespace std;

// Returns the minimum distance of every cell
// from the nearest bomb using Multi-Source BFS.
vector<vector<int>> findDistance(vector<vector<char>> &mat)
{
    int n = mat.size();
    int m = mat[0].size();

    // Initialize the answer matrix with -1
    vector<vector<int>> ans(n, vector<int>(m, -1));

    // Queue for Multi-Source BFS
    queue<pair<int, int>> q;

    // Add all bomb cells to the queue
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            // Bomb cell
            if (mat[i][j] == 'B')
            {
                ans[i][j] = 0;
                q.push({i, j});
            }

            // Wall cell
            else if (mat[i][j] == 'W')
            {
                ans[i][j] = -1;
            }
        }
    }

    // Traverse all reachable cells
    while (!q.empty())
    {
        auto curr = q.front();
        q.pop();

        int i = curr.first;
        int j = curr.second;

        // Move Down
        if (i + 1 < n && mat[i + 1][j] == 'O' && ans[i + 1][j] == -1)
        {
            ans[i + 1][j] = ans[i][j] + 1;
            q.push({i + 1, j});
        }

        // Move Up
        if (i - 1 >= 0 && mat[i - 1][j] == 'O' && ans[i - 1][j] == -1)
        {
            ans[i - 1][j] = ans[i][j] + 1;
            q.push({i - 1, j});
        }

        // Move Right
        if (j + 1 < m && mat[i][j + 1] == 'O' && ans[i][j + 1] == -1)
        {
            ans[i][j + 1] = ans[i][j] + 1;
            q.push({i, j + 1});
        }

        // Move Left
        if (j - 1 >= 0 && mat[i][j - 1] == 'O' && ans[i][j - 1] == -1)
        {
            ans[i][j - 1] = ans[i][j] + 1;
            q.push({i, j - 1});
        }
    }

    return ans;
}

int main()
{
    vector<vector<char>> mat = {{'O', 'O', 'O'}, {'W', 'B', 'B'}, {'W', 'O', 'O'}};

    vector<vector<int>> ans = findDistance(mat);

    for (auto &row : ans)
    {
        for (auto &x : row)
        {
            cout << x << " ";
        }
        cout << endl;
    }

    return 0;
}
Java
import java.util.*;

class GFG {

    // Returns the minimum distance of every cell
    // from the nearest bomb using Multi-Source BFS.
    static ArrayList<ArrayList<Integer> >
    findDistance(char[][] mat)
    {
        int n = mat.length;
        int m = mat[0].length;

        // Initialize the answer matrix with -1
        ArrayList<ArrayList<Integer> > ans
            = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            ans.add(new ArrayList<>());
            for (int j = 0; j < m; j++) {
                ans.get(i).add(-1);
            }
        }

        // Queue for Multi-Source BFS
        Queue<int[]> q = new LinkedList<>();

        // Add all bomb cells to the queue
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // Bomb cell
                if (mat[i][j] == 'B') {
                    ans.get(i).set(j, 0);
                    q.offer(new int[] { i, j });
                }

                // Wall cell
                else if (mat[i][j] == 'W') {
                    ans.get(i).set(j, -1);
                }
            }
        }

        // Traverse all reachable cells
        while (!q.isEmpty()) {

            int[] curr = q.poll();

            int i = curr[0];
            int j = curr[1];

            // Move Down
            if (i + 1 < n && mat[i + 1][j] == 'O'
                && ans.get(i + 1).get(j) == -1) {

                ans.get(i + 1).set(j,
                                   ans.get(i).get(j) + 1);
                q.offer(new int[] { i + 1, j });
            }

            // Move Up
            if (i - 1 >= 0 && mat[i - 1][j] == 'O'
                && ans.get(i - 1).get(j) == -1) {

                ans.get(i - 1).set(j,
                                   ans.get(i).get(j) + 1);
                q.offer(new int[] { i - 1, j });
            }

            // Move Right
            if (j + 1 < m && mat[i][j + 1] == 'O'
                && ans.get(i).get(j + 1) == -1) {

                ans.get(i).set(j + 1,
                               ans.get(i).get(j) + 1);
                q.offer(new int[] { i, j + 1 });
            }

            // Move Left
            if (j - 1 >= 0 && mat[i][j - 1] == 'O'
                && ans.get(i).get(j - 1) == -1) {

                ans.get(i).set(j - 1,
                               ans.get(i).get(j) + 1);
                q.offer(new int[] { i, j - 1 });
            }
        }

        return ans;
    }

    public static void main(String[] args)
    {
        char[][] mat = { { 'O', 'O', 'O' },
                         { 'W', 'B', 'B' },
                         { 'W', 'O', 'O' } };

        ArrayList<ArrayList<Integer> > ans
            = findDistance(mat);

        for (ArrayList<Integer> row : ans) {
            for (int x : row)
                System.out.print(x + " ");
            System.out.println();
        }
    }
}
Python
from collections import deque

# Returns the minimum distance of every cell
# from the nearest bomb using Multi-Source BFS.
def findDistance(mat):

    n = len(mat)
    m = len(mat[0])

    # Initialize the answer matrix with -1
    ans = [[-1] * m for _ in range(n)]

    # Queue for Multi-Source BFS
    q = deque()

    # Add all bomb cells to the queue
    for i in range(n):
        for j in range(m):

            # Bomb cell
            if mat[i][j] == 'B':
                ans[i][j] = 0
                q.append((i, j))

            # Wall cell
            elif mat[i][j] == 'W':
                ans[i][j] = -1

    # Traverse all reachable cells
    while q:

        i, j = q.popleft()

        # Move Down
        if i + 1 < n and mat[i + 1][j] == 'O' and ans[i + 1][j] == -1:
            ans[i + 1][j] = ans[i][j] + 1
            q.append((i + 1, j))

        # Move Up
        if i - 1 >= 0 and mat[i - 1][j] == 'O' and ans[i - 1][j] == -1:
            ans[i - 1][j] = ans[i][j] + 1
            q.append((i - 1, j))

        # Move Right
        if j + 1 < m and mat[i][j + 1] == 'O' and ans[i][j + 1] == -1:
            ans[i][j + 1] = ans[i][j] + 1
            q.append((i, j + 1))

        # Move Left
        if j - 1 >= 0 and mat[i][j - 1] == 'O' and ans[i][j - 1] == -1:
            ans[i][j - 1] = ans[i][j] + 1
            q.append((i, j - 1))

    return ans

# Driver Code
if __name__ == "__main__":
    mat = [
        ['O', 'O', 'O'],
        ['W', 'B', 'B'],
        ['W', 'O', 'O']
    ]

    ans = findDistance(mat)

    for row in ans:
        print(*row)
C#
using System;
using System.Collections.Generic;

class GFG {
    
    // Returns the minimum distance of every cell
    // from the nearest bomb using Multi-Source BFS.
    static List<List<int> > findDistance(char[, ] mat)
    {
        int n = mat.GetLength(0);
        int m = mat.GetLength(1);

        // Initialize the answer matrix with -1
        List<List<int> > ans = new List<List<int> >();

        for (int i = 0; i < n; i++) {
            List<int> row = new List<int>();

            for (int j = 0; j < m; j++)
                row.Add(-1);

            ans.Add(row);
        }

        // Queue for Multi-Source BFS
        Queue<(int, int)> q = new Queue<(int, int)>();

        // Add all bomb cells to the queue
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                // Bomb cell
                if (mat[i, j] == 'B') {
                    ans[i][j] = 0;
                    q.Enqueue((i, j));
                }

                // Wall cell
                else if (mat[i, j] == 'W') {
                    ans[i][j] = -1;
                }
            }
        }

        // Traverse all reachable cells
        while (q.Count > 0) {
            var(i, j) = q.Dequeue();

            // Move Down
            if (i + 1 < n && mat[i + 1, j] == 'O'
                && ans[i + 1][j] == -1) {
                ans[i + 1][j] = ans[i][j] + 1;
                q.Enqueue((i + 1, j));
            }

            // Move Up
            if (i - 1 >= 0 && mat[i - 1, j] == 'O'
                && ans[i - 1][j] == -1) {
                ans[i - 1][j] = ans[i][j] + 1;
                q.Enqueue((i - 1, j));
            }

            // Move Right
            if (j + 1 < m && mat[i, j + 1] == 'O'
                && ans[i][j + 1] == -1) {
                ans[i][j + 1] = ans[i][j] + 1;
                q.Enqueue((i, j + 1));
            }

            // Move Left
            if (j - 1 >= 0 && mat[i, j - 1] == 'O'
                && ans[i][j - 1] == -1) {
                ans[i][j - 1] = ans[i][j] + 1;
                q.Enqueue((i, j - 1));
            }
        }

        return ans;
    }

    static void Main()
    {
        char[, ] mat = { { 'O', 'O', 'O' },
                         { 'W', 'B', 'B' },
                         { 'W', 'O', 'O' } };

        List<List<int> > ans = findDistance(mat);

        foreach(var row in ans)
        {
            foreach(var x in row) Console.Write(x + " ");
            Console.WriteLine();
        }
    }
}
JavaScript
// Returns the minimum distance of every cell
// from the nearest bomb using Multi-Source BFS.
function findDistance(mat)
{
    const n = mat.length;
    const m = mat[0].length;

    // Initialize the answer matrix with -1
    const ans
        = Array.from({length : n}, () => Array(m).fill(-1));

    // Queue for Multi-Source BFS
    const q = [];
    let front = 0;

    // Add all bomb cells to the queue
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {

            // Bomb cell
            if (mat[i][j] === "B") {
                ans[i][j] = 0;
                q.push([ i, j ]);
            }

            // Wall cell
            else if (mat[i][j] === "W") {
                ans[i][j] = -1;
            }
        }
    }

    // Traverse all reachable cells
    while (front < q.length) {

        const [i, j] = q[front++];

        // Move Down
        if (i + 1 < n && mat[i + 1][j] === "O"
            && ans[i + 1][j] === -1) {

            ans[i + 1][j] = ans[i][j] + 1;
            q.push([ i + 1, j ]);
        }

        // Move Up
        if (i - 1 >= 0 && mat[i - 1][j] === "O"
            && ans[i - 1][j] === -1) {

            ans[i - 1][j] = ans[i][j] + 1;
            q.push([ i - 1, j ]);
        }

        // Move Right
        if (j + 1 < m && mat[i][j + 1] === "O"
            && ans[i][j + 1] === -1) {

            ans[i][j + 1] = ans[i][j] + 1;
            q.push([ i, j + 1 ]);
        }

        // Move Left
        if (j - 1 >= 0 && mat[i][j - 1] === "O"
            && ans[i][j - 1] === -1) {

            ans[i][j - 1] = ans[i][j] + 1;
            q.push([ i, j - 1 ]);
        }
    }

    return ans;
}

// Driver Code
const mat = [
    [ "O", "O", "O" ], [ "W", "B", "B" ], [ "W", "O", "O" ]
];

const ans = findDistance(mat);

for (const row of ans)
    console.log(row.join(" "));

Output
2 1 1 
-1 0 0 
-1 1 1 
Comment