|
| 1 | +# 图的表示 |
| 2 | + |
| 3 | +图的邻接表和邻接矩阵表示最为常用,但是有时需要建图时这两种表示效率不是很高,因为需要构造每个结点和每一条边。此时使用一些隐式的表示方法可以提升建图效率。 |
| 4 | + |
| 5 | +### [word-ladder](https://leetcode-cn.com/problems/word-ladder/) |
| 6 | + |
| 7 | +```Python |
| 8 | +class Solution: |
| 9 | + def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: |
| 10 | + |
| 11 | + N, K = len(wordList), len(beginWord) |
| 12 | + |
| 13 | + find_end = False |
| 14 | + for i in range(N): |
| 15 | + if wordList[i] == endWord: |
| 16 | + find_end = True |
| 17 | + break |
| 18 | + |
| 19 | + if not find_end: |
| 20 | + return 0 |
| 21 | + |
| 22 | + wordList.append(beginWord) |
| 23 | + N += 1 |
| 24 | + |
| 25 | + # clustering nodes for efficiency compare to adjacent list |
| 26 | + cluster = collections.defaultdict(list) |
| 27 | + for i in range(N): |
| 28 | + node = wordList[i] |
| 29 | + for j in range(K): |
| 30 | + cluster[node[:j] + '*' + node[j + 1:]].append(node) |
| 31 | + |
| 32 | + # bidirectional BFS |
| 33 | + visited_start, visited_end = set([beginWord]), set([endWord]) |
| 34 | + bfs_start, bfs_end = collections.deque([beginWord]), collections.deque([endWord]) |
| 35 | + step = 2 |
| 36 | + while bfs_start and bfs_end: |
| 37 | + |
| 38 | + # start |
| 39 | + num_level = len(bfs_start) |
| 40 | + while num_level > 0: |
| 41 | + node = bfs_start.popleft() |
| 42 | + for j in range(K): |
| 43 | + key = node[:j] + '*' + node[j + 1:] |
| 44 | + for n in cluster[key]: |
| 45 | + if n in visited_end: |
| 46 | + return step * 2 - 2 |
| 47 | + if n not in visited_start: |
| 48 | + visited_start.add(n) |
| 49 | + bfs_start.append(n) |
| 50 | + num_level -= 1 |
| 51 | + |
| 52 | + # end |
| 53 | + num_level = len(bfs_end) |
| 54 | + while num_level > 0: |
| 55 | + node = bfs_end.popleft() |
| 56 | + for j in range(K): |
| 57 | + key = node[:j] + '*' + node[j + 1:] |
| 58 | + for n in cluster[key]: |
| 59 | + if n in visited_start: |
| 60 | + return step * 2 - 1 |
| 61 | + if n not in visited_end: |
| 62 | + visited_end.add(n) |
| 63 | + bfs_end.append(n) |
| 64 | + num_level -= 1 |
| 65 | + step += 1 |
| 66 | + |
| 67 | + return 0 |
| 68 | +``` |
| 69 | + |
0 commit comments