Trang

Thứ Bảy, 1 tháng 1, 2011

1132. Knight Moves

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

public class Main {

    /**
     * http://acm.tju.edu.cn/toj/showp1132.html
     * @author hunglee
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {

        StreamTokenizer in = new StreamTokenizer(new BufferedReader(
                new InputStreamReader(System.in)));
        
        String xx, yy;
        int iS, jS, iF, jF, i, j, ik, jk;
        final int[] di = {-2, -1, 1, 2, 2, 1, -1, -2};
        final int[] dj = {1, 2, 2, 1, -1, -2, -2, -1};
        Queue<Integer> q;
        while (in.nextToken() != StreamTokenizer.TT_EOF) {
            xx = in.sval;
            in.nextToken();
            yy = in.sval;
            iS = xx.charAt(1) - '0' + 1;
            jS = xx.charAt(0) - 'a' + 2;
            iF = yy.charAt(1) - '0' + 1;
            jF = yy.charAt(0) - 'a' + 2;

            if (iS == iF && jS == jF) {
                System.out.print("To get from ");
                System.out.print(xx + " to " + yy);
                System.out.println(" takes 0 knight moves.");
                continue;
            }
            int[][] board = new int[12][12]; //2 -> 9
            for (i = 0; i <= 11; ++i)
                board[i][0] = board[i][1] = 
                    board[i][10] = board[i][11] = -1;
            for (j = 0; j <= 11; ++j)
                board[0][j] = board[1][j] = 
                    board[10][j] = board[11][j] = -1;
            
            q = new LinkedList<Integer>();
            board[iS][jS] = 1;
            q.add(iS); q.add(jS);
            while (!q.isEmpty()) {
                i = q.remove(); j = q.remove();
                for (int k = 0; k < 8; ++k) {
                    ik = i + di[k];
                    jk = j + dj[k];
                    if (ik == iF && jk == jF) {
                        System.out.print("To get from ");
                        System.out.print(xx + " to " + yy);
                        System.out.print(" takes " + (board[i][j]));
                        System.out.println(" knight moves.");
                        k = 8;
                        q.clear();
                        break;
                    }
                    if (board[ik][jk] == 0) {
                        board[ik][jk] = board[i][j] + 1;
                        q.add(ik); q.add(jk);
                    }
                }
            }
        }
    }

}

Không có nhận xét nào:

Đăng nhận xét