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

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →