LeetCode 1222: Queens That Can Attack the King Solution

Master LeetCode problem 1222 (Queens That Can Attack the King), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1222. Queens That Can Attack the King

Problem Explanation

Explanation:

To solve this problem, we can iterate through all possible directions (8 directions in total) from the king's position and check if there is a queen in that direction. We can start from the king's position and move in each direction until we either reach the edge of the board or find a queen. If we find a queen in a particular direction, we add it to the result.

  • We can define the 8 directions as offsets in x and y directions: dx = [-1, -1, -1, 0, 0, 1, 1, 1] and dy = [-1, 0, 1, -1, 1, -1, 0, 1].
  • We iterate through each direction and increment the x and y coordinates by the corresponding offsets until we find a queen or reach the edge of the board. :

Solution Code

class Solution {
    public List<List<Integer>> queensAttacktheKing(int[][] queens, int[] king) {
        List<List<Integer>> result = new ArrayList<>();
        Set<String> queenSet = new HashSet<>();
        for (int[] queen : queens) {
            queenSet.add(queen[0] + "," + queen[1]);
        }
        
        int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
        int[] dy = {-1, 0, 1, -1, 1, -1, 0, 1};
        
        for (int i = 0; i < 8; i++) {
            int x = king[0];
            int y = king[1];
            
            while (x >= 0 && x < 8 && y >= 0 && y < 8) {
                if (queenSet.contains(x + "," + y)) {
                    result.add(Arrays.asList(x, y));
                    break;
                }
                x += dx[i];
                y += dy[i];
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1222 (Queens That Can Attack the King)?

This page provides optimized solutions for LeetCode problem 1222 (Queens That Can Attack the King) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1222 (Queens That Can Attack the King)?

The time complexity for LeetCode 1222 (Queens That Can Attack the King) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1222 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1222 in Java, C++, or Python.

Back to LeetCode Solutions