LeetCodeから島周辺の問題に取り組んでいますが、実際の解決策はありますが、5817/5833テストケースのみを渡します。私はそれを成功と見なしますが、明らかに、非常に大きなサイズの "島"を扱うには十分効率的ではなく、パフォーマンス上の問題の原因を突き止めなければ、 "島周辺"の問題に慣れていない人のために、ここにLeetCodeページへのリンクがあります。私は言語で自分自身をrefamiliarizeし、うまくいけば自分自身にいくつかの新しいトリックを教えるためにPythonで問題を解決してきたので、それはちょうど誰かが私を改善する手助けができることを私は非効率的にやっているものになるかもしれアイランドペリメーションアルゴリズムが遅すぎる
。効率性の点で、以下のアルゴリズムで目に見える問題を誰も見ることができますか?
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
start = self.locateIsland(grid)
return self.islandHelp(grid, start)
def islandHelp(self, grid, start):
# get the perimeter of this position
p = self.getPerimeter(grid, start)
# mark this position as visited so we don't count it repeatedly
grid[start[0]][start[1]] = 2
# offsets to current positions to find land to the sides
sides = [[-1, 0], [0, 1], [1, 0], [0, -1]]
for side in sides:
newPos = [(start[0] + side[0]), (start[1] + side[1])]
if ((newPos[0] in range(len(grid))) and
(newPos[1] in range(len(grid[newPos[0]]))) and
(grid[newPos[0]][newPos[1]] == 1)):
# recursively find perimeter of connected land
p += self.islandHelp(grid, newPos)
return p
def getPerimeter(self, grid, pos):
p = 0
# offsets to find the neighboring positions
sides = [[-1, 0], [0, 1], [1, 0], [0, -1]]
for side in sides:
if (((pos[0] + side[0]) in range(len(grid))) and
((pos[1] + side[1]) in range(len(grid[pos[0] + side[0]])))):
if (grid[pos[0] + side[0]][pos[1] + side[1]] == 0):
# in bounds of grid, but not a land mass, add to perimeter
p += 1
else:
# out of bounds means edge of grid, add to perimeter
p += 1
return p
def locateIsland(self, grid):
# iterate through the grid to find a 1 and use that as start position
for r in range(len(grid)):
for c in range(len(grid[r])):
if (grid[r][c] == 1):
return (r, c)
return (-1, -1)
再帰、バックトラッキングなどすべてを行わないようにしてください。単純にする。 –
このリンクは、問題の説明にはつながりません。それを提供してください。おそらく輪郭トレース? http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/alg.html –