Queen's Attack II Discussions | Algorithms | HackerRank
We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static int queensAttack(int n, int k, int r_q, int c_q, List<List<Integer>> obstacles) {
Set<String> obstacleSet = new HashSet<>();
for (List<Integer> obs : obstacles) {
obstacleSet.add(obs.get(0) + "-" + obs.get(1));
}
int[][] directions = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}, // vertical and horizontal
{-1, -1}, {-1, 1}, {1, -1}, {1, 1} // diagonals
};
int attackableSquares = 0;
for (int[] dir : directions) {
int r = r_q + dir[0];
int c = c_q + dir[1];
while (r >= 1 && r <= n && c >= 1 && c <= n && !obstacleSet.contains(r + "-" + c)) {
attackableSquares++;
r += dir[0];
c += dir[1];
}
}
return attackableSquares;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] firstMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int n = Integer.parseInt(firstMultipleInput[0]);
int k = Integer.parseInt(firstMultipleInput[1]);
String[] secondMultipleInput = bufferedReader.readLine().replaceAll("\\s+$", "").split(" ");
int r_q = Integer.parseInt(secondMultipleInput[0]);
int c_q = Integer.parseInt(secondMultipleInput[1]);
List<List<Integer>> obstacles = new ArrayList<>();
IntStream.range(0, k).forEach(i -> {
try {
obstacles.add(
Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList())
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
int result = Result.queensAttack(n, k, r_q, c_q, obstacles);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Queen's Attack II
You are viewing a single comment's thread. Return to all comments →
//JAVA15: import java.io.; import java.util.; import java.util.stream.*;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}