(SPOJ) O Tabuleiro Esburacado - Solution

Link to the problem: http://br.spoj.com/problems/TABULE12/

Given the moves that the horse must take, the solution below tries to reach every new position until there is no more moves available or until it reaches a hole.


import java.io.*;
import java.util.*;

class Main {
    public int[][] matrix;
    public int[] vi = {0,-2,-1,1,2,2,1,-1,-2};
    public int[] vj = {0,1,2,2,1,-1,-2,-2,-1};
    public int[] movements;
       
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        matrix = new int[8][8];
        matrix[4][1] = -1;
        matrix[4][2] = -1;
        matrix[2][2] = -1;
        matrix[3][5] = -1;
       
        String line = br.readLine();
        int numMovements = Integer.parseInt(line);
       
        line = br.readLine();
        String[] s = line.split(" ");

        int currI = 4;
        int currJ = 4;
        int countMoves = 0;
        for (int i = 0; i < numMovements; i++) {
            int nextI = currI+vi[Integer.parseInt(s[i])];
            int nextJ = currJ+vj[Integer.parseInt(s[i])];
            countMoves++;
            if (matrix[nextI][nextJ] == -1) {
                break;
            }
            currI = nextI;
            currJ = nextJ;           
        }
       
        bw.write(countMoves+"\n");
       
        bw.flush();
        bw.close();
       
        return;
    }
   
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
       
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Powers of Two - Solução

(Coderbyte) Dash Insert II - Solução

(CoderByte) Number Search - Solução