I tried solving Leetcode 01 Matrix problem. It is running too slow when solved using DFS approach.
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1
Input:
[[0,0,0],
[0,1,0],
[0,0,0]]
Output:
[[0,0,0],
[0,1,0],
[0,0,0]]
Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
class Solution(object):
def updateMatrix(self, matrix):
if not matrix or not matrix[0]:
return []
m, n = len(matrix), len(matrix[0])
op = [[-1 for _ in range(n)] for _ in range(m)]
directions = [(1,0), (-1,0), (0, 1), (0, -1)]
def dfs(i,j):
if matrix[i][j] == 0:
return 0
if op[i][j] != -1:
return op[i][j]
matrix[i][j] = -1
closest_zero = float('inf')
for direction in directions:
x,y = direction[0] + i , direction[1] + j
if 0 <= x < m and 0 <= y < n and matrix[x][y] != -1:
closest_zero = min(dfs(x,y), closest_zero)
closest_zero += 1
matrix[i][j] = 1
return closest_zero
for i in range(m):
for j in range(n):
if matrix[i][j] == 1 and op[i][j] == -1:
op[i][j] = dfs(i,j)
elif matrix[i][j] == 0:
op[i][j] = 0
return op
It is running too slowly and I don't understand what is the reason for that. Most optimised solution have solved this using BFS.