It is leetcode #200, number of islands. My code is
JavaScript
x
17
17
1
def numIslands(self, grid: List[List[str]]) -> int:
2
def bfs(i,j):
3
q = deque([[i,j]])
4
while q:
5
r,c = q.popleft()
6
if 0<=r<len(grid) and 0<=c<len(grid[0]) and grid[r][c]=="1":
7
grid[r][c]="0"
8
q += [[r + 1, c], [r - 1, c], [r, c - 1], [r, c + 1]]
9
count = 0
10
for i in range(len(grid)):
11
for j in range(len(grid[0])):
12
if grid[i][j]=="1":
13
count+=1
14
bfs(i,j)
15
16
return count
17
It works fine.
But when I change the bfs
function into
JavaScript
1
9
1
def bfs(i,j):
2
q = deque([[i,j]])
3
while q:
4
r,c = q.popleft()
5
grid[r][c]="0"
6
for d in [[r + 1, c], [r - 1, c], [r, c - 1], [r, c + 1]]:
7
if 0<=d[0]<len(grid) and 0<=d[1]<len(grid[0]) and grid[d[0]][d[1]]=="1":
8
q.append(d)
9
It gives me the Time Limit Exceeded error, what could the reasons be? I think these two codes are nearly identical?
Advertisement
Answer
You are visiting the same state many times:
Change to the following:
JavaScript
1
11
11
1
def bfs(i,j):
2
q = deque([[i,j]])
3
grid[i][j]="0"
4
5
while q:
6
r,c = q.popleft()
7
for d in [[r + 1, c], [r - 1, c], [r, c - 1], [r, c + 1]]:
8
if 0<=d[0]<len(grid) and 0<=d[1]<len(grid[0]) and grid[d[0]][d[1]]=="1":
9
grid[d[0]][d[1]]="0"
10
q.append(d)
11