熱門文章

2026年4月4日 星期六

ZeroJudge 解題筆記:d057. 11494 - Queen

作者:王一哲
日期:2026年4月4日


ZeroJudge 題目連結:d057. 11494 - Queen

解題想法


可能的步數有 3 種:
  1. 不需要移動,回傳 0。
  2. 在同一列、同一欄、斜直線上,回傳 1。
  3. 其它狀況,走 2 步一定會走到,回傳 2。


Python 程式碼


使用時間約為 10 ms,記憶體約為 3.6 MB,通過測試。
import sys

def find_step(x1, y1, x2, y2):  # 輸入起點、終點找步數
    if x1 == x2 and y1 == y2: return 0  # 不需要移動,回傳 0
    if x1 == x2 or y1 == y2: return 1  # 在同一欄或列,回傳 1
    if x2 - x1 == y2 - y1:  # 右上、左下斜直線
        dx = x2 - x1  # x 方向位移
        dy = y2 - y1  # y 方向位移
        if 1 <= x1 + dy <= 8 and 1 <= y1 + dx <= 8:  # 沒出界
            return 1  # 回傳 1
    if x2 - x1 == y1 - y2:  # 左上、右下斜直線
        dx = x2 - x1  # x 方向位移
        dy = y2 - y1  # y 方向位移
        if 1 <= x1 - dy <= 8 and 1 <= y1 - dx <= 8:  # 沒出界
            return 1  # 回傳 1
    # 其它狀況,最多只要水平、垂直各走一步,回傳 2
    return 2

result = []
lines = sys.stdin.readlines()
for line in lines:
    if line.strip() == "0 0 0 0": break
    step = find_step(*map(int, line.split()))
    result.append(f"{step:d}\n")
sys.stdout.write("".join(result))


C++ 程式碼


使用時間約為 1 ms,記憶體約為 64 kB,通過測試。
#include <cstdio>

/* 輸入起點、終點找步數 */
int find_step(int x1, int y1, int x2, int y2) {
    if (x1 == x2 && y1 == y2) return 0;  // 不需要移動,回傳 0
    if (x1 == x2 || y1 == y2) return 1;  // 在同一欄或列,回傳 1
    if (x2 - x1 == y2 - y1) {  // 右上、左下斜直線
        int dx = x2 - x1, dy = y2 - y1;  // x、y 方向位移
        int x = x1 + dy, y = y1 + dx;  // 移動後的位置
        if (x >= 1 && x <= 8 && y >= 1 && y <= 8) {  // 沒出界
            return 1;  // 回傳 1
        }
    }
    if (x2 - x1 == y1 - y2) {  // 左上、右下斜直線
        int dx = x2 - x1, dy = y2 - y1;  // x、y 方向位移
        int x = x1 - dy, y = y1 - dx;  // 移動後的位置
        if (x >= 1 && x <= 8 && y >= 1 && y <= 8) {  // 沒出界
            return 1;  // 回傳 1
        }
    }
    // 其它狀況,最多只要水平、垂直各走一步,回傳 2
    return 2;
}

int main() {
    int x1, y1, x2, y2;
    while(scanf("%d %d %d %d", &x1, &y1, &x2, &y2) != EOF) {
        if (x1 == 0 && y1 == 0 && x2 == 0 && y2 == 0) break;
        printf("%d\n", find_step(x1, y1, x2, y2));
    }
    return 0;
}


沒有留言:

張貼留言