Created
November 10, 2017 20:49
-
-
Save guillermogotre/27d4f349b362575d7d6c5bfcaff01497 to your computer and use it in GitHub Desktop.
HackerRank - Algorithm / Implementation / Queen's Attack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
import java.text.*; | |
import java.math.*; | |
import java.util.regex.*; | |
public class Solution { | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int n = in.nextInt(); | |
int k = in.nextInt(); | |
int rQueen = in.nextInt()-1; | |
int cQueen = in.nextInt()-1; | |
/* | |
d0 | r0 | d1 | |
------------ | |
r1 | R | r2 | |
------------ | |
d2 | r3 | d3 | |
d0 -> (d0.c+d0.r = R.c+R.r) <r | |
r0 -> =c <r | |
d1 -> (d1.c-d1.r = R.c-R.r) <r | |
r1 -> =r <c | |
r2 -> =r >c | |
d2 -> (d1.c-d1.r = R.c-R.r) >r | |
r3 -> =c >r | |
d3 -> (d0.c+d0.r = R.c+R.r) >r | |
*/ | |
int d0,d1,d2,d3,r0,r1,r2,r3; | |
d0 = r0 = d1 = r1 = Integer.MIN_VALUE; | |
r2 = d2 = r3 = d3 = Integer.MAX_VALUE; | |
for(int a0 = 0; a0 < k; a0++){ | |
int rObstacle = in.nextInt()-1; | |
int cObstacle = in.nextInt()-1; | |
if(cObstacle == cQueen){ | |
if(rObstacle < rQueen && rObstacle > r0) | |
r0 = rObstacle; | |
else if(rObstacle > rQueen && rObstacle < r3) | |
r3 = rObstacle; | |
}else if(rObstacle == rQueen){ | |
if(cObstacle < cQueen && cObstacle > r1) | |
r1 = cObstacle; | |
else if(cObstacle > cQueen && cObstacle < r2) | |
r2 = cObstacle; | |
}else if((cObstacle - rObstacle) == (cQueen - rQueen)){ | |
if(rObstacle < rQueen && rObstacle > d0) | |
d0 = rObstacle; | |
else if(rObstacle > rQueen && rObstacle < d3) | |
d3 = rObstacle; | |
}else if((cObstacle + rObstacle) == (cQueen + rQueen)){ | |
if(rObstacle < rQueen && rObstacle > d1) | |
d1 = rObstacle; | |
else if(rObstacle > rQueen && rObstacle < d2) | |
d2 = rObstacle; | |
} | |
} | |
int total = 0; | |
/* | |
0 1 2 3 | |
___________ | |
0 |x o o x | |
------------ | |
1 |0 x o x | |
------------ | |
2 |0 0 x x | |
------------- | |
3 |x x x R | |
*/ | |
total += Math.min((rQueen - Math.max(0,d0+1)),cQueen); | |
total += (rQueen - Math.max(0,r0+1)); | |
total += Math.min((rQueen - Math.max(0,d1+1)),(n - 1 - cQueen)); | |
total += (cQueen - Math.max(0,r1+1)); | |
total += (Math.min(r2-1,n-1) - cQueen); | |
total += Math.min((Math.min(d2-1,n-1) - rQueen),cQueen); | |
total += (Math.min(r3-1,n-1) - rQueen); | |
total += Math.min((Math.min(d3-1,n-1) - rQueen),(n - 1 - cQueen)); | |
System.out.println(total); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment