lc 773. Sliding Puzzle

too short a time to find the easist way of this problem, but it definately exists.

brute force way of a bfs, record every state you've visit, return the depth of your travel.

class Solution:
    def __init__(self):
        self.neighbor=[[1,3],[0,2,4],[1,5],[0,4],[1,3,5],[2,4]]
        self.done=set()
    def zeroLoc(self,b):
        for i in range(6):
            if b[i]=='0':
                return i
    def next(self,b):
        if ''.join(b)=='123450':
            return True
        z=self.zeroLoc(b)
        n=self.neighbor[z]
        ans=[]
        for l in n:
            bb=b[:]
            tem=bb[z]
            bb[z]=bb[l]
            bb[l]=tem
            if ''.join(bb) not in self.done:
                self.done.add(''.join(bb))
                ans.append(bb)
        return ans
    def slidingPuzzle(self, board):
        """
        :type board: List[List[int]]
        :rtype: int
        """
        b=[board[i//3][i%3] for i in range(6)]
        b=[str(i) for i in b]
        cur=[b]
        ans=0
        if ''.join(b)=='123450':
            return 0
        self.done.add(''.join(b))
        while len(cur)>0:
            ans+=1
            next_cur=[]
            for bb in cur:
                t=self.next(bb)
                if t==True:
                    return ans-1
                next_cur+=t
            cur=next_cur
        return -1

 

posted @ 2018-09-07 13:24  Cloud.9  阅读(236)  评论(0编辑  收藏  举报