파이썬을 사용하여 spoj 문제를 해결하려고합니다. 내 알고리즘은 O (N^2)해야하지만, 여전히 TLE는
내 방법은 단지 멀티 소스 BFS이다 ... 리턴된다.SPOJ 비트 맵
- "ANS"
- 인쇄 ANS
문제 링크라는 이름의 2D 목록으로 최단 거리를 저장, 각각 '1'의 모든 1
if __name__ == '__main__':
n = int(input()) #reading number of test cases
for k in range(n):
(row, col) = input().split() #row and col
row = int(row)
col = int(col)
#store the bitmap
bitmap = []
for i in range(row):
line = input()
bitmap.append(line)
ans = [[False for i in range(col)] for j in range(row)] #init a 2d array to store answer
front = []
num_element = row*col
processed = 0
for i in range(row):
for j in range(col):
if(bitmap[i][j] == '1'):
ans[i][j] = 0
front.append((i,j))
processed = processed +1
while processed < num_element:
new_list = []
for node in front:
i = node[0]
j = node[1]
new_distance = ans[i][j] + 1
if(i> 0 and ans[i-1][j] is False):
ans[i-1][j] =new_distance
new_list.append((i-1,j))
processed = processed +1
if(i< row -1 and ans[i+1][j] is False):
ans[i+1][j] =new_distance
new_list.append((i+1,j))
processed = processed +1
if(j > 0 and ans[i][j-1] is False):
ans[i][j-1] =new_distance
new_list.append((i,j-1))
processed = processed +1
if(j < col -1 and ans[i][j+1] is False):
ans[i][j+1] =new_distance
new_list.append((i,j+1))
processed = processed +1
front = new_list
#print the answer
for line in ans:
s = map(str, line)
print(" ".join(s))
input()
당신의 큰 O 복잡성이 최적입니다. –
@ n.m. 하지만 여전히 TLE입니다. 저의 구현이 너무 어리 석 었나요? ... – Bear
글쎄,이 전체 BFS 일은 정말로 여기에 필요하지 않습니다. 간단한 패스 또는 2 개의 배열로 충분합니다. 하지만 실행 시간에 많은 영향을 미치지는 않습니다 (제가 확인했습니다). –