classSolution(object):# 本题采用广度遍历方法defladderLength(self, beginWord, endWord, wordList):"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
word_set =set(wordList)
cur_word =[]
cur_word.append(beginWord)
ans =1
stash =[]while cur_word:for word in cur_word:if word == endWord:return ans
for i inrange(len(word)):for s in"abcdefghijklmnopqrstuvwxyz":
new_word = word[:i]+s+word[i+1:]if new_word in word_set:
word_set.remove(new_word)
stash.append(new_word)
ans +=1
cur_word = stash
stash =[]return0
classSolution(object):defshortestPathBinaryMatrix(self, grid):"""
:type grid: List[List[int]]
:rtype: int
"""
n, m =len(grid),len(grid[0])if n==1and m==1:return1if grid[0][0]==1or grid[n-1][m-1]==1:return-1
ans =1
q =[]
stash =[]
q.append([0,0])
visted =[[0]* m for _ inrange(n)]
visted[0][0]=1
movies =[(-1,0),(1,0),(-1,1),(1,-1),(0,-1),(0,1),(1,1),(-1,-1)]while q:
x, y = q.pop(0)
ans = visted[x][y]
ans +=1for dx, dy in movies:if x+dx == n -1and y+dy == m -1:return ans
if-1<x+dx<n and-1<y+dy<m:if0==visted[x+dx][y+dy]and grid[x+dx][y+dy]!=1:
stash.append([x+dx, y+dy])
visted[x+dx][y+dy]= ans
iflen(q)==0:
q=stash
stash=[]return-1