Queen's Attack II Discussions | Algorithms | HackerRank
  • + 0 comments

    //JAVA15: import java.io.; import java.util.; import java.util.stream.*;

    class Result {

    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();
    }
    

    }