Similar Problems
Similar Problems not available
Matrix Cells In Distance Order - Leetcode Solution
Companies:
LeetCode: Matrix Cells In Distance Order Leetcode Solution
Difficulty: Easy
Topics: math matrix sorting array
Problem Statement: Given a matrix of size m x n containing 0's and 1's, where 0 represents water and 1 represents land, we need to find the cells in the matrix with minimum Manhattan distance from all the water cells and return them in any order.
A cell in the matrix (r, c) is considered to have a Manhattan distance dx + dy from every water cell, where dx and dy are the horizontal and vertical distances between the cells respectively.
Solution: The problem is to find the cells with minimum Manhattan distance from all the water cells. We can observe that the cells with minimum distance would be those which lie closest to the water cells. So, one approach to solve the problem can be to iteratively expand the search for each water cell and keep adding the cells with minimum distance to a result list.
Algorithm:
- Initialize an empty queue and a visited set.
- Iterate over the matrix and enqueue all water cells.
- Initialize an empty result list and a distance variable.
- While the queue is not empty:
- Dequeue a cell from the queue and mark it as visited.
- Calculate the Manhattan distance of the cell from every visited cell and update the distance variable.
- Add the current cell to the result list.
- Enqueue all adjacent cells that are not visited and not water cells.
- Return the result list.
Code:
class Solution:
def allCellsDistOrder(self, m: int, n: int, r0: int, c0: int) -> List[List[int]]:
queue = collections.deque([(r0, c0)])
visited = set(queue)
result = []
distance = 0
while queue:
for _ in range(len(queue)):
r, c = queue.popleft()
result.append([r, c])
distance = max(distance, abs(r-r0) + abs(c-c0))
for dr, dc in [(0,1),(0,-1),(1,0),(-1,0)]:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and (nr, nc) not in visited:
queue.append((nr, nc))
visited.add((nr, nc))
return sorted(result, key=lambda cell: abs(cell[0]-r0) + abs(cell[1]-c0))
We first initialize an empty queue and a visited set. We iterate over the matrix and enqueue all water cells. Then, we initialize an empty result list and a distance variable.
While the queue is not empty, we dequeue a cell and mark it as visited. We calculate the Manhattan distance of the cell from every visited cell and update the distance variable. We add the current cell to the result list. We also enqueue all adjacent cells that are not visited and not water cells.
Finally, we return the result list sorted by the Manhattan distance from the starting cell.
Matrix Cells In Distance Order Solution Code
1