Sunday, June 2, 2013

Topcoder SRM 576 DIV 2 L2 ArcadeManao

// Topcoder SRM 576 DIV 2 L2 ArcadeManao

import java.util.*;
import java.math.*;

//rename the class name before submitting
public class ArcadeManao {
    public static void main(String[] args) {
        ArcadeManao obj = new ArcadeManao();
        Object o =
                obj.shortestLadder(
                        null,
                        0,
                        0
                        );
        System.out.println(o);
    }

    static boolean found;

    public int shortestLadder(String[] level, int coinRow, int coinColumn) {
        int row = level.length;
        int col = level[0].length();
        int L;
        for (L = 0; L < row; L++) {
            boolean[][] visited = new boolean[row][col];
            found = false;
            Search(L, level, row, 1, coinRow, coinColumn, visited);
            if (found)
                break;
        }
        return L;
    }

    private void Search(int L, String[] lev, int fromRow, int fromCol, int coinR,
            int coinC, boolean[][] visited) {
        if (found)
            return;
        if (fromRow < 1 || fromRow > lev.length || fromCol < 1
                || fromCol > lev[0].length())
            return;
        if (visited[fromRow - 1][fromCol - 1])
            return;
        else
            visited[fromRow - 1][fromCol - 1] = true;
        if (lev[fromRow - 1].charAt(fromCol - 1) == '.')
            return;
        if (fromRow == coinR && fromCol == coinC)
            found = true;
        // to left
        if (fromCol > 1 && lev[fromRow - 1].charAt(fromCol - 1 - 1) == 'X')
            Search(L, lev, fromRow, fromCol - 1, coinR, coinC, visited);
        // to right
        if (fromCol < lev[0].length()
                && lev[fromRow - 1].charAt(fromCol - 1 + 1) == 'X')
            Search(L, lev, fromRow, fromCol + 1, coinR, coinC, visited);
        for (int LL = 1; LL <= L; LL++) {
            // up
            int newR = fromRow - LL;
            Search(L, lev, newR, fromCol, coinR, coinC, visited);
            // down
            newR = fromRow + LL;
            Search(L, lev, newR, fromCol, coinR, coinC, visited);
        }
        return;
    }
}

No comments:

Post a Comment