Nearest Bus Stop From a House - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional integer matrix containing 0s, 1s, 2s, and 3s where

0 represents an empty cell
1 represents a wall
2 represents a house
3 represents a bus stop
Return the shortest distance from any house to any bus stop. You can move up, down, left, and right but you can't move through a house or a wall cell. If there's no solution, return -1.

Constraints

n, m ≤ 250 where n and m are the number of rows and columns in matrix

Example 1

Input

matrix = [

    [2, 1, 3, 0],

    [1, 1, 1, 1],

    [0, 3, 0, 0],

    [0, 0, 0, 2]

]

Output

3

Explanation

We can go from the house at matrix[3][3] to bus stop at matrix[2][1].



Solution :



title-img




                        Solution in C++ :

int r, c;
int dp[250][250];
int solve(vector<vector<int>>& m) {
    r = m.size();
    c = m[0].size();
    queue<pair<int, int>> q;
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            if (m[i][j] == 2) {
                dp[i][j] = 0;
                q.emplace(i, j);
            } else {
                dp[i][j] = 1e9;
            }
        }
    }
    while (q.size()) {
        auto [x, y] = q.front();
        q.pop();
        if (m[x][y] == 3) return dp[x][y];
        int dx[4]{-1, 0, 1, 0};
        int dy[4]{0, 1, 0, -1};
        for (int k = 0; k < 4; k++) {
            int nx = x + dx[k];
            int ny = y + dy[k];
            if (nx < 0 || nx >= r || ny < 0 || ny >= c || m[nx][ny] == 1) continue;
            if (dp[nx][ny] > 1 + dp[x][y]) {
                dp[nx][ny] = 1 + dp[x][y];
                q.emplace(nx, ny);
            }
        }
    }
    return -1;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[][] matrix) {
        int N = matrix.length;
        if (N == 0)
            return 0;
        int M = matrix[0].length;

        int INF = 1000000;
        ArrayDeque<int[]> bfs = new ArrayDeque<int[]>();
        int[][] dist = new int[N][M];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < M; j++) {
                dist[i][j] = INF;
                if (matrix[i][j] == 2) {
                    // this is a house and a source in the bfs
                    dist[i][j] = 0;
                    bfs.add(new int[] {i, j});
                }
            }
        }

        int ans = INF;
        int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        while (!bfs.isEmpty()) {
            int[] cell = bfs.pollFirst();
            int d = dist[cell[0]][cell[1]];
            if (matrix[cell[0]][cell[1]] == 3) {
                ans = d;
                break;
            }
            for (int[] dir : dirs) {
                int newR = cell[0] + dir[0];
                int newC = cell[1] + dir[1];
                if (newR >= 0 && newR < N && newC >= 0 && newC < M && matrix[newR][newC] % 3 == 0
                    && dist[newR][newC] == INF) {
                    dist[newR][newC] = d + 1;
                    bfs.add(new int[] {newR, newC});
                }
            }
        }

        return (ans == INF ? -1 : ans);
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, A):
        R, C = len(A), len(A[0])
        queue = []
        for r, row in enumerate(A):
            for c, v in enumerate(row):
                if v == 2:
                    queue.append((r, c))
        dist = {loc: 0 for loc in queue}

        for r, c in queue:
            if A[r][c] == 3:
                return dist[r, c]
            for nr, nc in ((r - 1, c), (r, c - 1), (r + 1, c), (r, c + 1)):
                if 0 <= nr < R and 0 <= nc < C and A[nr][nc] != 1 and (nr, nc) not in dist:
                    queue.append((nr, nc))
                    dist[nr, nc] = dist[r, c] + 1

        return -1
                    


View More Similar Problems

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →