[Codewars] 103: Path Finder #2: shortest path

題目

Task

You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return the minimal number of steps to exit position [N-1, N-1] if it is possible to reach the exit from the starting position. Otherwise, return false in JavaScript/Python and -1 in C++/C#/Java.

Empty positions are marked .. Walls are marked W. Start and exit positions are guaranteed to be empty in all test cases.

我的答案

from collections import deque
from math import sqrt, floor

dirc = [[0, 1], [0, -1], [1, 0], [-1, 0]]
d = deque(maxlen=500)

def BFS(n, maze):
    while len(d) > 0:
        d0 = d.popleft()
        for i in range(4):
            x = d0[0] + dirc[i][0]
            y = d0[1] + dirc[i][1]
            if x < 0 or x >= n or y < 0 or y >= n:
                continue
            if maze[x * n + y] == 'W':
                continue
            if x == n - 1 and y == n - 1:
                return d0[2] + 1
            maze[x * n + y] = 'W'
            d.append([x, y, d0[2] + 1])
    return False

def path_finder(maze):
    n = floor(sqrt(len(maze)))
    if n == 1:
        return 0
    else:
        maze = [i for i in list(maze) if i !='\n']
        while len(d) > 0:
            d.pop()
        d.append([0, 0, 0])
        maze[0] = 'W'
        return BFS(n, maze)

其他精彩答案

def path_finder(maze):
    lst  = maze.split('\n')
    X, Y = len(lst)-1, len(lst[0])-1
    seen = {(x,y) for x,row in enumerate(lst) for y,c in enumerate(row) if c=='W'} | {(0,0)}
    end, bag, turn = (X,Y), {(0,0)}, 0
    
    while bag and end not in bag:
        bag = { (a,b) for a,b in {(x+dx,y+dy) for x,y in bag for dx,dy in ((0,1), (0,-1), (1,0), (-1,0))}
                      if 0 <= a <= X and 0 <= b <= Y} - seen
        seen |= bag
        turn += 1
    
    return bool(bag) and turn
def path_finder(maze):
    maze = list(map(list, maze.splitlines()))
    lenmaze_y, lenmaze_x = len(maze), len(maze[0])
    queue = [(0, 0, 0)]
    
    while queue:
        y,x,cnt = queue.pop(0)        
        if x >= 0 and y >= 0 and x < lenmaze_x and y < lenmaze_y:
            if maze[y][x] == '.':
                maze[y][x] = cnt
                directions = [(1, 0),(0, 1),(-1, 0),(0, -1)]
                for direction_y, direction_x in directions:
                    queue.append((y + direction_y, x + direction_x, cnt+1))
            if x == lenmaze_x-1 and y == lenmaze_y-1:
                return maze[y][x]
            
    return False
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末辑奈,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子魔市,更是在濱河造成了極大的恐慌,老刑警劉巖募闲,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件笔喉,死亡現(xiàn)場離奇詭異尸诽,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)绑改,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進(jìn)店門谢床,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人厘线,你說我怎么就攤上這事识腿。” “怎么了造壮?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵渡讼,是天一觀的道長。 經(jīng)常有香客問我耳璧,道長成箫,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任旨枯,我火速辦了婚禮蹬昌,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘攀隔。我一直安慰自己皂贩,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布昆汹。 她就那樣靜靜地躺著明刷,像睡著了一般。 火紅的嫁衣襯著肌膚如雪满粗。 梳的紋絲不亂的頭發(fā)上遮精,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天,我揣著相機(jī)與錄音败潦,去河邊找鬼。 笑死准脂,一個胖子當(dāng)著我的面吹牛劫扒,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播狸膏,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼沟饥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起贤旷,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤广料,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后幼驶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體艾杏,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年盅藻,在試婚紗的時候發(fā)現(xiàn)自己被綠了购桑。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡氏淑,死狀恐怖勃蜘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情假残,我是刑警寧澤缭贡,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站辉懒,受9級特大地震影響阳惹,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜耗帕,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一穆端、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧仿便,春花似錦体啰、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至闻坚,卻和暖如春沽翔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背窿凤。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工仅偎, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人雳殊。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓橘沥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親夯秃。 傳聞我的和親對象是個殘疾皇子座咆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評論 2 361