Wednesday, December 24, 2014

Count Luck - Maze

Most of the maze question are related to DFS graph search, can be solved by recursive way.

This one is from HackerRank

https://www.hackerrank.com/challenges/count-luck/copy-from/10625563


Problem Statement from hackerrank
Hermione Granger is lost in the Forbidden Forest while collecting some herbs for her magical potion. The forest is magical and has only 1 exit point which magically transports her back to the Hogwarts School of Wizardy and Witch Craft.
Forest can be considered as a grid of NxM size. Each cell in the forest is either empty (represented by '.') or has a tree (represented by 'X'). Hermione can move through empty cell, but not through cells with tree on it. She can only travel LEFT, RIGHT, UP, DOWN. Her position in the forest is indicated by the marker 'M' and the location of the exit point is indicated by '*'. Top-left corner is indexed (0, 0).
.X.X......X
.X*.X.XXX.X
.XX.X.XM...
......XXXX.
In the above forest, Hermione is located at index (2, 7) and exit is at (1, 2). Each cell is indexed according to Matrix Convention
She starts her commute back to the exit and every time she encounters more than one option to move, she waves her wand and the correct path is illuminated and she proceeds in that way. It is guaranteed that there is only one path to each reachable cell from the starting cell. Can you tell us if she waved her wand exactly K times or not? Ron will be impressed if she is able to do so.
The key here is to find the ONLY path from M to *, then trace it back, and count the point where Hermione has multiple choices. 
public class Solution {
    public static class Node{
        int r;int c; Node pre;
        public Node(int r, int c){this.r = r; this.c = c;}
    }
    public static void visit(char[][] maz, int startR, int startC, boolean[][] seen,  Node pre, Node tail){
        if(startR<0 || startC<0 || startR>=maz.length || startC>=maz[0].length || seen[startR][startC])
            return;
        if(maz[startR][startC]=='X')
            return;
        if(maz[startR][startC]=='*'){
            tail.pre = pre;
            return;       
        }
        seen[startR][startC] = true;
        Node n = new Node(startR, startC);
        n.pre = pre;
        visit(maz, startR-1, startC, seen,  n, tail);
        visit(maz, startR+1, startC, seen,  n, tail);
        visit(maz, startR, startC-1, seen,  n, tail);
        visit(maz, startR, startC+1, seen,  n, tail);
    }
    
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try(Scanner conin = new Scanner(System.in)){
            int t = conin.nextInt();
            while(t-->0){
                int row = conin.nextInt();
                int col = conin.nextInt();
                int startR=0, startC=0;
                int endR=0, endC=0;
                char[][] maz = new char[row][col];
                for(int r=0; r<row; r++){
                    String str = conin.next();
                    int index = str.indexOf("M");
                    if(index>=0){
                        startR=r;startC=index;
                    }
                    index = str.indexOf("*");
                    if(index>=0){
                        endR=r;endC=index;
                    }
                    maz[r] = str.toCharArray();
                }
                int k=conin.nextInt();
                boolean[][] seen = new boolean[row][col];
                Node tail = new Node(endR, endC);
                Node head = null;
                visit(maz, startR, startC, seen, head, tail);                 
                int counter = 0;
                Node n = tail.pre;
                while(n!=null){
                    //System.out.println(n.r + "-" + n.c);
                    int option = 0;
                    if(n.r-1>=0 && n.r-1<row && maz[n.r-1][n.c]=='.')
                        option++;
                    if(n.r+1>=0 && n.r+1<row && maz[n.r+1][n.c]=='.')
                        option++;
                    if(n.c-1>=0 && n.c-1<col && maz[n.r][n.c-1]=='.')
                        option++;
                    if(n.c+1>=0 && n.c+1<col && maz[n.r][n.c+1]=='.')
                        option++;
                    if(option>2 || (n == tail.pre&&option>1) || (n.r==startR&&n.c==startC&&option>1) || (n.pre!=null && n.pre.r==startR&&n.pre.c==startC&&option>1))
                        counter++;
                    n = n.pre;                    
                }
                
                System.out.println(counter==k?"Impressed":"Oops!");
            }
        }
    }
}



Tuesday, December 23, 2014

Star

This one is from hacker rank.

https://www.hackerrank.com/challenges/stars


Problem Statement from the hacker rank
Little John has drawn N stars on his paper where each star has a weight vi. He draws a straight line that divides the paper into two parts such that each part has a subset of stars in them. Let the weight of each part be the summation of weights of the stars in the part. He wants to draw the line such that the difference in the sum of weights between the two parts is as small as possible while maximizing the smaller part's weight.
Your task is to compute the weight of smaller part corresponding to this line where no stars are allowed to be on the line and line can be of any slope.
Input Format
The first line of the input contains an integer N.
Each of next N lines contains three integers xi and yi specifying the positions of ith star and vi.
No three points lie on a line.
The key here is the formular to find if point is on left or right side of a line:
position = sign( (Bx-Ax)*(Y-Ay) - (By-Ay)*(X-Ax) )
0 on the line, and positive on one side, negative on the other side.

this is O(n^3) solution
public class Solution {
    public static class Point{
        long x; long y; long w;
        Point(long x, long y, long w){this.x = x; this.y = y; this.w = w;}
        long onLine(Point p1, Point p2){
            return (p1.x - p2.x)*(this.y-p1.y)-(p1.y-p2.y)*(this.x-p1.x);
        }
    }

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        try(Scanner conin = new Scanner(System.in)){
            int num = conin.nextInt();
            Point[] points = new Point[num];
            for(int i=0; i<num; i++){
                points[i] = new Point(conin.nextLong(), conin.nextLong(), conin.nextLong());
            }
            long maxSum = 0;
            for(int i=0; i<num; i++){
                for(int j=i+1; j<num; j++){
                    long leftSum = 0;
                    long rightSum = 0;
                    for(int k=0; k<num; k++){
                        if(!(k==i || k==j)){
                            long left = points[k].onLine(points[i], points[j]);
                            if(left>0)
                                leftSum += points[k].w;
                            else
                                rightSum += points[k].w;
                        }                        
                    }
                    
                    long[] sums = new long[]{leftSum, rightSum, points[i].w, points[j].w};
                    Arrays.sort(sums);
                    long sum = Math.min(sums[0]+sums[3], sums[1]+sums[2]);
                    maxSum = Math.max(maxSum, sum);
                    
                    //sum = Math.min(sums[0], sums[1]+sums[2]+sums[3]);
                    //maxSum = Math.max(maxSum, sum);
                    
                    sum = Math.min(sums[0]+sums[1], sums[2]+sums[3]);
                    maxSum = Math.max(maxSum, sum);
                    
                    sum = Math.min(sums[0]+sums[1]+sums[2], sums[3]);
                    maxSum = Math.max(maxSum, sum);
                    
                }
            }
            System.out.println(maxSum);
        }
    }
}