Knight's Shortest Path on Chessboard

后端 未结 16 1321
情深已故
情深已故 2020-11-30 16:42

I\'ve been practicing for an upcoming programming competition and I have stumbled across a question that I am just completely bewildered at. However, I feel as though it\'s

16条回答
  •  难免孤独
    2020-11-30 17:12

    The O(1) answer above [https://stackoverflow.com/a/8778592/4288232 by Mustafa Serdar Şanlı] isn't really working. (Check (1,1) or (3,2) or (4,4), aside for the obvious edge cases of (1,0) or (2,2)).

    Below is a much uglier solution (python), which does work (with added "tests"):

    def solve(x,y):
            x = abs(x)
            y = abs(y)
            if y > x:
                temp=y
                y=x
                x=temp  
            if (x==2 and y==2):
                return 4
            if (x==1 and y==0):
                return 3
    
        if(y == 0 or float(y) / float(x) <= 0.5):
            xClass = x % 4
            if (xClass == 0):
                initX = x/2
            elif(xClass == 1):
                initX = 1 + (x/2)
            elif(xClass == 2):
                initX = 1 + (x/2)
            else:
                initX = 1 + ((x+1)/2)
    
            if (xClass > 1):
                return initX - (y%2)
            else:
                return initX + (y%2)
        else:
            diagonal = x - ((x-y)/2)
            if((x-y)%2 == 0):
                if (diagonal % 3 == 0):
                    return (diagonal/3)*2
                if (diagonal % 3 == 1):
                    return ((diagonal/3)*2)+2
                else:
                    return ((diagonal/3)*2)+2
            else:
                return ((diagonal/3)*2)+1
    
    
    def test():
        real=[
        [0,3,2,3,2,3,4,5,4,5,6,7,6,7],
        [3,2,1,2,3,4,3,4,5,6,5,6,7,8],
        [2,1,4,3,2,3,4,5,4,5,6,7,6,7],
        [3,2,3,2,3,4,3,4,5,6,5,6,7,8],
        [2,3,2,3,4,3,4,5,4,5,6,7,6,7],
        [3,4,3,4,3,4,5,4,5,6,5,6,7,8],
        [4,3,4,3,4,5,4,5,6,5,6,7,6,7],
        [5,4,5,4,5,4,5,6,5,6,7,6,7,8],
        [4,5,4,5,4,5,6,5,6,7,6,7,8,7],
        [5,6,5,6,5,6,5,6,7,6,7,8,7,8],
        [6,5,6,5,6,5,6,7,6,7,8,7,8,9],
        [7,6,7,6,7,6,7,6,7,8,7,8,9,8]]
    
        for x in range(12):
            for y in range(12):
                res = solve(x,y)
                if res!= real[x][y]:
                    print (x, y), "failed, and returned", res, "rather than", real[x][y]
                else:
                   print (x, y), "worked. Cool!"
    
    test()
    

提交回复
热议问题