2010-01-11 Finding Shortest Path using Breadth First Search Algorithm
Finding Shortest Path using Breadth First Search Algorithm
面白い問題があったので解いてみました。問題の詳細は、出題者さんのエントリでご確認ください。
さて試験問題です。内容は、壁とスペースで構成された迷路が与えられたとき、スタート地点からゴール地点に至る最短経路を求めよ、というものです。
人生を書き換える者すらいた。: 人材獲得作戦・4 試験問題ほか
実装は以下となりました。Python3.1.1を使用し、BFS + 既知の最短経路での刈り込みを行なっています。
#!/usr/local/bin/python3.1 -t import collections import sys def solve(a, s, g): dps = (( 0, -1), ( 1, 0), ( 0, 1), (-1, 0)) shortest = {} queue = collections.deque([[s]]) while queue: path = queue.popleft() p = path[-1] if p in shortest: if len(path) < len(shortest[p]): shortest[p] = path else: continue else: shortest[p] = path if p == g: yield path continue for dp in dps: np = p[0] + dp[0], p[1] + dp[1] if np not in path: if a[np[1]][np[0]] != '*': queue.append(path + [np]) if __name__ == '__main__': a = [] for i, l in enumerate(sys.stdin): l = l.strip() if 'S' in l: s = (l.index('S'), i) if 'G' in l: g = (l.index('G'), i) a.append(l) for path in sorted(solve(a, s, g), key=lambda x: len(x)): for i, r in enumerate(a): for j, c in enumerate(r): if (j, i) == g: print('G', end='') elif (j, i) in path: print('$', end='') else: print(c, end='') print()
制限時間がある中のコーディングであったため汚いですね。そのような中でもしっかりと実装出来るようになりたいものです。
追記(2010/1/12)
ゴールを発見した後も検索を続けていたので、打ち切りました。
:
if p == g:
yield path
continue
:
追記(2010/1/21)
Visualizing Dijkstra's, and A* Search Algorithm - agwの日記として、ダイクストラのアルゴリズムとA*検索アルゴリズムについての考察を記載しました。
トラックバック - http://d.hatena.ne.jp/agw/20100111/1263288853
リンク元
- 144 http://okajima.air-nifty.com/b/2010/01/post-abc6.html
- 6 http://b.hatena.ne.jp/entry/okajima.air-nifty.com/b/2010/01/post-abc6.html
- 5 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja-JP-mac:official&hs=E7l&q=user+postfix+has+same+user+ID+as+_postfix&btnG=検索&lr=lang_ja&aq=f&oq=
- 4 http://a.hatena.ne.jp/guttyon/
- 4 http://b.hatena.ne.jp/entry/d.hatena.ne.jp/agw/20071126/1196152803
- 3 http://fastladder.com/reader/
- 3 http://www.google.co.jp/hws/search?q=kd木++アルゴリズム&client=fenrir&safe=off&adsafe=off&hl=ja&lr=lang_ja&ie=UTF-8&oe=UTF-8&start=10&br=
- 3 http://www.google.com/search?client=safari&rls=en&q=snow+leopard+dscl+user&ie=UTF-8&oe=UTF-8
- 2 http://images.google.com.tw/imgres?imgurl=http://f.hatena.ne.jp/images/fotolife/a/agw/20090427/20090427001726.png&imgrefurl=http://d.hatena.ne.jp/agw/20090426/1240818639&usg=__Uku-2-oqv8OAreOXvf-Kzq96nZA=&h=459&w=459&sz=22&hl=zh-TW&start=396&um=1&tbnid=Ge
- 2 http://okajima.air-nifty.com/b/2009/12/post-0f2e.html


























