京东8.19笔试
A了两道,最后一道卡住了。
最后想出来的时候已经没时间了。
不知道下面这个方法对不对:有大佬帮忙看一下吗?
n, m = map(int, input().split())
board = []
for _ in range(n):
board.append(list(input()))
dp = [[float("inf")] * m for _ in range(n)]
if board[0][0] == ".":
dp[0][0] = 0
# print(dp1)
for i in range(n):
for j in range(m):
if board[i][j] == "." and dp[i][j] != float("inf"):
k = 1
while j+k < m and board[i][j+k] == ".":
dp[i][j+k] = min(dp[i][j+k], dp[i][j]+1)
k += 1
k = 1
while i+k < n and board[i+k][j] == ".":
dp[i+k][j] = min(dp[i+k][j], dp[i][j]+1)
k += 1
k = 1
while i+k < n and j+k < m and board[i+k][j+k] == ".":
dp[i+k][j+k] = min(dp[i+k][j+k], dp[i][j]+1)
k += 1
print(-1) if dp[n-1][m-1] == float("inf") else print(dp[n-1][m - 1])
最后想出来的时候已经没时间了。
不知道下面这个方法对不对:有大佬帮忙看一下吗?
n, m = map(int, input().split())
board = []
for _ in range(n):
board.append(list(input()))
dp = [[float("inf")] * m for _ in range(n)]
if board[0][0] == ".":
dp[0][0] = 0
# print(dp1)
for i in range(n):
for j in range(m):
if board[i][j] == "." and dp[i][j] != float("inf"):
k = 1
while j+k < m and board[i][j+k] == ".":
dp[i][j+k] = min(dp[i][j+k], dp[i][j]+1)
k += 1
k = 1
while i+k < n and board[i+k][j] == ".":
dp[i+k][j] = min(dp[i+k][j], dp[i][j]+1)
k += 1
k = 1
while i+k < n and j+k < m and board[i+k][j+k] == ".":
dp[i+k][j+k] = min(dp[i+k][j+k], dp[i][j]+1)
k += 1
print(-1) if dp[n-1][m-1] == float("inf") else print(dp[n-1][m - 1])
全部评论
你这复杂度是n的3次方,应该能过50-60,拿bfs使用set维护,或者3维dp,3维dp最后一个纬度表示方向,同一个方向不用+1,不同方向+1,这题我直接看错了,刚开始没看到可以移动k,gg
相关推荐
点赞 评论 收藏
分享
点赞 评论 收藏
分享