|
发表于 2015-1-25 16:04:02
|
显示全部楼层
本帖最后由 挥舞乾坤 于 2015-1-25 16:46 编辑
先发出来测试一下,抛砖引玉了,代码效率太低了,5*6要10几秒,6*6,几分钟,先测试一下功能吧,一会出去喝大酒,回来再改
1*6的问题改过了,但效率还是硬伤啊
- def maze():
- '之后加上判断输入是否合法的代码'
- str_map = input('输入一个字符串格式的迷宫地图(SBW.,....,....,..BE):')
- #处理字符串,返回二维列表形式的地图及元组形式的地图范围
- limit,data = str_to_list(str_map)
-
- #遍历所有可达路径,返回列表
- list_path = get_path(data,limit)
- #路径加速减速方面的处理
- list_path = chuli(list_path)
- #计算耗时
- min_time,min_path = calc(list_path)
- print('地图大小:%d * %d' % limit)
- print('#',min_path, sep = '')
- print('最低耗时:%d' % min_time)
-
- def str_to_list(str_map):
- '处理字符串,返回一个二维列表形式的地图列表'
- str_map = str_map.upper()
- list_map = [ list(x) for x in str_map.split(',')]
- map_limit = (len(list_map),len(list_map[0]))
- return map_limit,list_map
- def get_path(data,limit):
- '便利所有可达路径'
- result = []
- fx = [[0, 1, 'R'], [1, 0, 'D'], [0, -1, 'L'], [-1, 0, 'U']]
- x_limit,y_limit = limit
-
- def move(path, maps, path_stack = [(0,0)]):
- '这里有点问题,由于用的是递归,代码效率太低了,6*6太久,5*6勉强可以,囧'
- x, y = path_stack[-1]
- if (x, y) == (x_limit - 1,y_limit - 1):
- result.append(path)
- path_stack.pop()
- return
-
- for i in fx:
- x, y = path_stack[-1]
- x, y = x + i[0], y + i[1]
- if x not in range(x_limit) or y not in range(y_limit) \
- or (x,y) in path_stack or maps[x][y] == 'W':
- x = max(min(x, x_limit - 1), 0)
- y = max(min(y, y_limit - 1), 0)
- continue
- path_stack.append((x,y))
- if maps[x][y] == 'B':
- move(path + i[2] + 'B', maps)
- else:
- move(path + i[2], maps)
- path_stack.pop()
- move('',data)
-
- return result
- def chuli(list_path):
- new_list = []
- for each in list_path:
- if each.count('B') == 1:
- each = each.replace('B','')
- if each.count('B') == 2:
- if each.rindex('B') - each.index('B') < 3:
- each = each.replace('B','')
- elif each.count('B') > 2:
- first = each.index('B')
- end = each.rindex('B') - len(each) + 1
- each = each.replace('B','')
- each = each[:first] + 'B' + each[first:]
- each = each[:end] + 'B' + each[end:]
-
- new_list.append(each)
- return new_list
-
- def calc(list_path):
- min_sep = 100
- min_path = ''
- for each in list_path:
- count = 0
- spend = -1
- for s in each:
- if s == 'B':
- count += 1
- spend = -spend
- elif spend == 1:
- count += 1
- else:
- count += 2
- if count < min_sep:
- min_sep = count
- min_path = each
- return min_sep,min_path
-
- if __name__ == '__main__':
- maze()
复制代码
|
评分
-
查看全部评分
|