# 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) {
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) {
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```
```

## Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

## Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

## Lazy White Falcon

White Falcon just solved the data structure problem below using heavy-light decomposition. Can you help her find a new solution that doesn't require implementing any fancy techniques? There are 2 types of query operations that can be performed on a tree: 1 u x: Assign x as the value of node u. 2 u v: Print the sum of the node values in the unique path from node u to node v. Given a tree wi

## Ticket to Ride

Simon received the board game Ticket to Ride as a birthday present. After playing it with his friends, he decides to come up with a strategy for the game. There are n cities on the map and n - 1 road plans. Each road plan consists of the following: Two cities which can be directly connected by a road. The length of the proposed road. The entire road plan is designed in such a way that if o

## Heavy Light White Falcon

Our lazy white falcon finally decided to learn heavy-light decomposition. Her teacher gave an assignment for her to practice this new technique. Please help her by solving this problem. You are given a tree with N nodes and each node's value is initially 0. The problem asks you to operate the following two types of queries: "1 u x" assign x to the value of the node . "2 u v" print the maxim

## Number Game on a Tree

Andy and Lily love playing games with numbers and trees. Today they have a tree consisting of n nodes and n -1 edges. Each edge i has an integer weight, wi. Before the game starts, Andy chooses an unordered pair of distinct nodes, ( u , v ), and uses all the edge weights present on the unique path from node u to node v to construct a list of numbers. For example, in the diagram below, Andy