Knight's Shortest Path on Chessboard

后端 未结 16 1290
情深已故
情深已故 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:04

    Here is a C version based on Mustafa Serdar Şanlı code that works for a finit board:

    #include 
    #include 
    
    #define test(x1, y1, x2, y2) (sx == x1 && sy == y1 &&tx == x2 &&ty == y2) || (sx == x2 && sy == y2 && tx == x1 && ty==y1)
    
    int distance(int sx, int sy, int tx, int ty) {
        int x, y, t;
        double delta;
    
        // special corner cases 
        if (test(1, 1, 2, 2) || 
            test(7, 7, 8, 8) || 
            test(7, 2, 8, 1) || 
            test(1, 8, 2, 7))
            return 4;
    
        // axes symmetry 
        x = abs(sx - tx);
        y = abs(sy - ty);
    
        // diagonal symmetry 
        if (x < y) {
            t = x;
            x = y;
            y = t;
        }
    
        // 2 corner cases
        if (x == 1 && y == 0)
            return 3;
        if (x == 2 && y == 2)
            return 4;
    
        // main
        delta = x - y;
        if (y > delta) {
            return (int)(delta - 2 * floor((delta - y) / 3));
        }
        else {
            return (int)(delta - 2 * floor((delta - y) / 4));
        }
    }
    

    Test it here with proof against a recursive solution

提交回复
热议问题