Here's the source code
def list_sub(l_a, l_b):
return [i for i in l_a if not i in l_b or l_b.remove(i)]
def bi_direction_list_sub(l_a, l_b):
l_valid_path = [ ]
for i in l_a:
rev_i = (i % 10) * 10 + (i // 10)
if not i in l_b:
if not rev_i in l_b:
l_valid_path.append(i)
return l_valid_path
def get_map_list(teleports_string):
l_map = [ int(i) for i in teleports_string.split(',')]
l_map_bi_direction = [i for i in l_map]
for p in l_map:
p_rev = (p % 10) * 10 + (p // 10)
l_map_bi_direction.append(p_rev)
sorted(l_map_bi_direction)
return l_map_bi_direction
def get_path(l_tel, l_ret, last_path, last_pop):
l_working_path = bi_direction_list_sub(l_tel, l_ret)
sorted(l_working_path)
for p in l_working_path:
if str(p)[0] == str(last_path)[ len(str(last_path)) - 1 ]:
if every_node_be_traversed(l_ret) == False:
if p > last_pop:
return p
return 'dead'
def every_node_be_traversed(l_ret):
l_traversed_node = [str(path)[0] for path in l_ret]
for i in range(1, 9):
if not str(i) in l_traversed_node:
return False
if str(l_ret[len(l_ret) - 1])[1] != '1':
return False
return True
def remove_path_from_candidate(l_tmp_tel, path):
rev_path = (path % 10) * 10 + (path // 10 )
if path in l_tmp_tel:
l_tmp_tel.remove(path)
if rev_path in l_tmp_tel:
l_tmp_tel.remove(rev_path)
def add_candidate(l_tmp_tel, path):
rev_path = (path % 10) * 10 + (path // 10 )
if not path in l_tmp_tel:
l_tmp_tel.append(path)
if not rev_path in l_tmp_tel:
l_tmp_tel.append(rev_path)
def checkio(teleports_string):
l_ret = [ ]
l_tel = get_map_list(teleports_string)
l_tmp_tel = [i for i in l_tel]
last_path = 1
last_pop = 1
while every_node_be_traversed(l_ret) == False:
path = get_path(l_tmp_tel, l_ret, last_path, last_pop)
if path == 'dead': #dead end
if len(l_ret) == 0:
last_path = 1
last_pop = 1
else:
last_pop = l_ret.pop()
add_candidate(l_tmp_tel, last_pop)
if str(last_pop)[0] == '1':
last_path = 1
last = 1
continue
else:
last_path = l_ret[ len(l_ret) - 1]
continue
last_pop = 1
last_path = path
l_ret.append(path)
remove_path_from_candidate(l_tmp_tel, path)
l_tmp_tel = sorted(l_tmp_tel)
l_str_ret = [str(i)[0] for i in l_ret]
ret = ''.join(l_str_ret)+'1'
return ret
沒有留言:
張貼留言