fucking-algorithm
fucking-algorithm copied to clipboard
[bug][python] 752-open-the-lock
请在提交 bug 之前先搜索
- [x] 我已经搜索过 issues,没有发现相同的 bug。
出错的题目链接
https://leetcode.com/problems/open-the-lock/description/
报错信息
python解法中用的python3,即声明了return type,然而plusOne和minusOne都和openLock位于同一级并且定义在openLock之后,需要将plusOne和minusOne前移,并且参数中包含self,或者置于openLock中,在使用前定义
我的代码(已AC):
class Solution:
def openLock(self, deadends: List[str], target: str) -> int:
deads = set(deadends)
visited = set()
q = []
step = 0
q.append("0000")
visited.add("0000")
def plusOne(s: str, j: int) -> str:
ch = list(s)
if ch[j] == '9':
ch[j] = '0'
else:
ch[j] = str(int(ch[j])+1)
return "".join(ch)
def minusOne(s: str, j: int) -> str:
ch = list(s)
if ch[j] == '0':
ch[j] = '9'
else:
ch[j] = str(int(ch[j])-1)
return "".join(ch)
while q:
sz = len(q)
for i in range(sz):
cur = q.pop(0)
if cur in deads:
continue
if cur == target:
return step
for j in range(4):
up = plusOne(cur,j)
if up not in visited:
q.append(up)
visited.add(up)
down = minusOne(cur,j)
if down not in visited:
q.append(down)
visited.add(down)
step += 1
return -1
你是否愿意提交 PR 修复这个 bug?
- [X] 我愿意!