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 :
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
Kindergarten Adventures
Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti
View Solution →Mr. X and His Shots
A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M
View Solution →Jim and the Skyscrapers
Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space
View Solution →Palindromic Subsets
Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t
View Solution →Counting On a Tree
Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n
View Solution →Polynomial Division
Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie
View Solution →