Farthest Point From Water - Amazon Top Interview Questions


Problem Statement :


You are given a matrix matrix of 0s and 1s where 0 represents water and 1 represents land. Find the land with the largest Manhattan distance from water and return this distance. If there is no land or no water in the board, return -1.

Constraints

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

Example 1

Input

matrix = [
    [1, 1, 0],
    [1, 1, 0],
    [0, 0, 1]
]

Output

2

Explanation

grid[0][0] has a Manhattan distance of 2 to water.

Example 2

Input

matrix = [
    [1, 1],
    [1, 1]
]

Output

-1

Explanation

There is no water in this grid.

Example 3

Input

matrix = [
    [1, 1, 1, 1],
    [0, 1, 1, 1],
    [0, 0, 1, 0]
]

Output

3

Explanation

Land at grid[0][2] has a Manhattan distance of 3 to nearest water.



Solution :



title-img




                        Solution in C++ :

int solve(vector<vector<int>>& matrix) {  // Time and Space: O(N * M)
    int height = matrix.size();
    if (height == 0) return -1;

    int width = matrix[0].size();
    if (width == 0) return -1;

    queue<pair<int, int>> cell_queue;  // Push all zeroes into queue
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (matrix[row][col] == 0) cell_queue.push(make_pair(row, col));
        }
    }

    int dir[5] = {1, 0, -1, 0, 1};
    int max_dist = -1;
    int curr_dist = 0;

    while (!cell_queue.empty()) {  // BFS
        int size = cell_queue.size();
        curr_dist++;

        for (int i = 0; i < size; i++) {
            int row = cell_queue.front().first;
            int col = cell_queue.front().second;
            cell_queue.pop();

            for (int d = 1; d <= 4; d++) {
                int r = row + dir[d - 1];
                int c = col + dir[d];

                if (r < 0 || c < 0 || r >= height || c >= width || matrix[r][c] == 0) continue;

                matrix[r][c] = 0;  // Set cell to 0, so we don't count it anymore
                max_dist = curr_dist;
                cell_queue.push(make_pair(r, c));
            }
        }
    }

    return max_dist;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    static class Point {
        int x;
        int y;

        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    public int solve(int[][] matrix) {
        ArrayDeque<Point> q = new ArrayDeque<>();
        int n = matrix.length;
        int m = matrix[0].length;

        // Stores distance of coordinate
        int[][] dis = new int[n][m];

        // Direction coordinates
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};

        int oo = Integer.MAX_VALUE;
        int cnt0 = 0;

        // Multisource BFS , add all 0s to the queue
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                if (matrix[i][j] == 0) {
                    q.add(new Point(i, j));
                    matrix[i][j] = -1;
                    dis[i][j] = 0;
                    ++cnt0;
                } else
                    dis[i][j] = oo;
            }
        }

        // Return -1 if there is no 0 or all all 0s
        if (cnt0 == 0 || cnt0 == n * m)
            return -1;

        int ans = -oo;
        while (!q.isEmpty()) {
            Point p = q.pollFirst();
            matrix[p.x][p.y] = -1;
            for (int i = 0; i < 4; ++i) {
                int newX = p.x + dx[i];
                int newY = p.y + dy[i];
                if (newX >= 0 && newX < n && newY >= 0 && newY < m && matrix[newX][newY] != -1) {
                    q.add(new Point(newX, newY));
                    dis[newX][newY] = Math.min(dis[newX][newY], 1 + dis[p.x][p.y]);
                }
            }
        }

        // Find maximum distance of any 1 to closest 0
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                ans = Math.max(ans, dis[i][j]);
            }
        }

        return ans;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix):
        m, n = len(matrix), len(matrix[0])

        def get(y, x):
            if 0 <= y < m and 0 <= x < n:
                return matrix[y][x]
            return math.inf

        for y in range(m):
            for x in range(n):
                if matrix[y][x] != 0:
                    matrix[y][x] = min(get(y - 1, x) + 1, get(y, x - 1) + 1)

        for y in range(m - 1, -1, -1):
            for x in range(n - 1, -1, -1):
                if matrix[y][x] != 0:
                    matrix[y][x] = min(matrix[y][x], get(y + 1, x) + 1, get(y, x + 1) + 1)

        max_dist = max(val for row in matrix for val in row)

        return -1 if max_dist in (math.inf, 0) else max_dist
                    


View More Similar Problems

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →