-
Notifications
You must be signed in to change notification settings - Fork 288
/
AC_two_end_BFS_n.py
44 lines (37 loc) · 1.22 KB
/
AC_two_end_BFS_n.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_two_end_BFS_n.py
# Create Date: 2015-03-29 15:10:46
# Usage: AC_two_end_BFS_n.py
# Descripton:
import string
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
start_set, end_set = set([start]), set([end])
n = len(start)
dis = 1
chars = string.ascii_lowercase
while start_set and end_set:
dis += 1
if len(start_set) < len(end_set):
start_set, end_set = end_set, start_set
new_start_set = set()
for word in start_set:
for idx in range(n):
for c in chars:
s = word[:idx] + c + word[idx+1:]
if s in end_set:
return dis
if s in dict:
new_start_set.add(s)
dict.remove(s)
start_set = new_start_set
return 0
# debug
s = Solution()
print s.ladderLength("hot", "dog", ["hot","dog"])