(UVA) Il Gioco dell'X - Solution

For this solution I used Depth-First Search.


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

class Main  {
    public static char[][] matrix;
    public static boolean[][] visited;
    public static int[] vi = {-1,-1,0,0,1,1};
    public static int[] vj = {-1,0,-1,1,0,1};
    public static int length;
    public static boolean blackWon;
   
    public static void dfs(int currI, int currJ) {
        if (currI < 0 || currJ < 0 || currI >= length || currJ >= length || matrix[currI][currJ] == 'w' || visited[currI][currJ] == true) {
            return;
        }
       
        if (currI == length-1) {
            blackWon = true;
            return;
        }
       
        visited[currI][currJ] = true;
        for (int i = 0; i < 6 && !blackWon; i++) {
            int nextI = currI+vi[i];
            int nextJ = currJ+vj[i];
            dfs(nextI, nextJ);
        }
    }
   
    public static void process() throws NumberFormatException, IOException {  
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        String line = br.readLine();
        length = Integer.parseInt(line);
        int numCase = 0;
        while (length != 0) {
            matrix = new char[length][length];
            visited = new boolean[length][length];
            for (int i = 0; i < length; i++) {
                line = br.readLine();
                for (int j = 0; j < length; j++) {
                    matrix[i][j] = line.charAt(j);
                }
            }
           
            blackWon = false;
            for (int j = 0; j < length; j++) {
                dfs(0, j); // check if black won
            }
           
            if (blackWon) {
                System.out.println(++numCase + " B");
            }
            else {
                System.out.println(++numCase + " W");
            }
           
            line = br.readLine();
            length = Integer.parseInt(line);
        }
                                                
        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) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução