(SPOJ) Robô - Solution

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

The solution below used Depth-First Search to find the path from the first to the last '1'.


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

class solucao {
    public int[][] matrix;
    public boolean[][] visited;
    public int[] vi = {-1,0,0,1};
    public int[] vj = {0,-1,1,0};
    public int rowEnd;
    public int colEnd;
    public int numRows;
    public int numCols;
   
    public void dfs(int currI, int currJ) {
        rowEnd = currI;
        colEnd = currJ;
        visited[currI][currJ] = true;
        for (int i = 0; i < 4; i++) {
            int nextI = currI+vi[i];
            int nextJ = currJ+vj[i];
            if (nextI > 0 && nextJ > 0 && nextI <= numRows && nextJ <= numCols && matrix[nextI][nextJ] == 1 && !visited[nextI][nextJ]) {
                dfs(nextI, nextJ);
                return;
            }
        }
    }
   
    public void process() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
      
        String line = br.readLine();
        String[] s = line.split(" ");
        numRows = Integer.parseInt(s[0]);
        numCols = Integer.parseInt(s[1]);
       
        line = br.readLine();
        s = line.split(" ");
        int rowStart = Integer.parseInt(s[0]);
        int colStart = Integer.parseInt(s[1]);
       
        matrix = new int[numRows+1][numCols+1];
        for (int i = 1; i <= numRows; i++) {
            line = br.readLine();
            s = line.split(" ");
            for (int j = 1; j <= numCols; j++) {
                matrix[i][j] = Integer.parseInt(s[j-1]);
            }
        }
       
        visited = new boolean[numRows+1][numCols+1];
        dfs(rowStart, colStart);
       
        bw.write(rowEnd + " " + colEnd + "\n");
       
        bw.flush();
        bw.close();
      
        return;
    }
  
    public static void main(String[] args) throws NumberFormatException, IOException {
        solucao m = new solucao();
        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