以下のようなコードを書きました。計算量がO(N)になっていると考えていて、PyPyなら十分通ると考えているのですが、ほとんどの結果がTLEになってしまいます。 計算時間を短縮し、ACする方法はあるのでしょうか。
python3
1def dig(tag,end): 2 h=tag[0] 3 w=tag[1] 4 delta=[(1,0),(-1,0),(0,1),(0,-1)] 5 next=set() 6 for d in delta: 7 if not h+d[0]<0 and not h+d[0]>=H and not w+d[1]<0 and not w+d[1]>=W and tag not in end: 8 next.add((h+d[0],w+d[1])) 9 return next 10 11H, W = map(int, input().split()) 12black_mass=set() 13 14for h in range(H): 15 line=input() 16 for w in range(W): 17 if line[w] == '#': 18 black_mass.add((h,w)) 19 20count=-1 21end=set() 22targets=black_mass 23next_que=set() 24while True: 25 count+=1 26 next_que=set() 27 for tag in targets: 28 next_que= next_que | dig(tag,end) 29 end.add(tag) 30 # print('next que',next_que) 31 # print('end:',end) 32 targets=next_que 33 if len(end) == H*W: 34 print(count) 35 exit(0) 36
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。