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

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →