4
我正試圖解決某個網站的編程挑戰問題,我不想在此提及。優化python代碼,減少分配/釋放時間
的問題是如下:
有一個方形板具有N * N個點。昆蟲從特定點開始(x1,y1)。如果| x1-x2 | + | y1-y2 |,它可以跳到任何點(x2,y2) < = S。另外,有些點含有昆蟲不能跳躍的水。 M跳可以採用多少種不同的路徑?請注意,它可以保持在同一點跳躍到位。
的整數N
,S
,M
給出,所以是初始板配置。
我很肯定我的解決方案是正確的,可以通過歸納法證明。我將棋盤轉換成一個圖形(鄰接列表),並在兩個點之間形成有效的昆蟲跳躍。那麼它只需要重複M次並更新路徑計數。
我主要關心的是代碼需要進行優化,以便它可以在多個測試用例上工作而不會分配/釋放太多時間,從而減慢運行時間。如果任何人都可以在算法本身中提出優化建議,那將會很棒。
謝謝!
import sys
#The board on which Jumping insect moves.
#The max size in any test case is 200 * 200
board = [['_']*200 for j in xrange(200)]
#Graph in the form of an adjancency list created from the board
G = [list() for i in xrange(200*200)]
def paths(N,M,S):
'''Calculates the total number of paths insect takes
The board size is N*N, Length of paths: M,
Insect can jusp from square u to square v if ||u-v|| <=S
Here ||u-v|| refers to the 1 norm'''
# Totals paths are modulo 1000000007
MOD = 1000000007
# Clearing adjacency list for this testcase
for i in xrange(N*N): del(G[i][:])
s = -1 #Starting point s
#Creating G adjacency list
# Point 'L' represents starting point
# Point 'P' cannot be accessed by the insect
for u in xrange(N*N):
x1, y1 = u/N, u%N
if board[x1][y1] == 'L': s = u
elif board[x1][y1] == 'P': continue
for j in xrange(S+1):
for k in xrange(S+1-j):
x2, y2 = x1+j, y1+k
if x2 < N and y2 < N and not board[x2][y2] == 'P':
v = x2*N+y2
G[u].append(v)
if not u == v: G[v].append(u)
if j > 0 and k > 0:
x2, y2 = x1+j, y1-k
if x2 < N and y2 >= 0 and not board[x2][y2] == 'P':
v = x2*N+y2
G[u].append(v)
G[v].append(u)
# P stores path counts
P = [[0 for i in xrange(N*N)] for j in xrange(2)]
# Setting count for starting position to 1
P[0][s] = 1
# Using shifter to toggle between prev and curr paths
shifter, prev, curr = 0, 0, 0
# Calculating paths
for i in xrange(M):
prev, curr = shifter %2, (shifter+1)%2
#Clearing Path counts on curr
for i in xrange(N*N): P[curr][i] = 0
for u in xrange(N*N):
if P[prev][u] == 0: continue
for v in G[u]:
P[curr][v] = (P[curr][v]+P[prev][u]) % MOD
shifter = (shifter+1)%2
return (sum(P[curr])%MOD)
#Number of testcases
num = int(sys.stdin.readline().split()[0])
results = []
# Reading in test cases
for i in xrange(num):
N, M, S = [int(j) for j in sys.stdin.readline().split()]
for j in xrange(N):
board[j][:N] = list(sys.stdin.readline().split()[0])
results.append(paths(N,M,S))
for result in results:
print result