Snakes and Ladders: The Quickest Way Up

  • + 0 comments

    Pthon

    BFS

    def bfs(node, squares):
        visited = set()
        q = []
        q.append(node)
        sentinel = None
        q.append(sentinel)
        movement = 0
        while(len(q)>0):
            n = q.pop(0)
           
            if(n is sentinel):
                if(q):
                    movement += 1
                    q.append(sentinel)
                    continue
                else:
                    return -1
            if (n.finish):
                return movement
            if(n in visited):
                continue
            visited.add(n)
            for i in n.edges:
                q.append(squares[i])
                
    def quickestWayUp(ladders, snakes):
        squares = {}
        dladders = {}
        dsnakes = {}
        for i in ladders:
            s1 = i[0]
            s2 = i[1]
            dladders[s1] = s2
        for i in snakes:
            s1 = i[0]
            s2 = i[1]
            dsnakes[s1] = s2
        for i in range(100, 0, -1):
            n = Node(i)
            squares[i] = n
            for j in range(i+1, i+7):
                if (j<=100):
                    if(j in dladders):
                        n.edges.append(dladders[j])
                    elif (j in dsnakes):
                        n.edges.append(dsnakes[j])
                    else:
                        n.edges.append(j)  
        # for i in range(1,101):
        #     print("n", squares[i].val)
        #     print(squares[i].edges)
        squares[100].finish=True
        return bfs(squares[1], squares)