Similar Problems

Similar Problems not available

Queens That Can Attack The King - Leetcode Solution

Companies:

LeetCode:  Queens That Can Attack The King Leetcode Solution

Difficulty: Medium

Topics: matrix array simulation  

Problem Statement: Given a chessboard of size n x n, find all the positions in which n queens can be placed on the board in such a way that no two queens attack each other, i.e., no two queens share the same row, column or diagonal.

Example: Input: n = 4 Output: [[0,1,2,3],[1,3,0,2]] Explanation: There are two solutions for this problem. The first solution has queens placed at (0,1), (1,3), (2,0), (3,2). The second solution has queens placed at (0,1), (1,3), (2,0), (3,2) in the same way but with rows and columns swapped.

Solution: The problem can be solved using backtracking. The algorithm for the problem can be as follows:

  1. Create an empty board of size n x n.
  2. Call the solve method with the board and n as the input.
  3. If all the queens are placed, return the board.
  4. For each row in the board, check for all the columns.
  5. If a queen can be placed at the current position, mark the position as visited and move to the next row.
  6. If no queen can be placed in the current row, backtrack to the previous row and try a different column.
  7. Once all the positions in the board have been visited, return the board.

Code: def solve(n): board = [[0 for x in range(n)] for y in range(n)]

if solve_util(board, 0, n) == False:
    return []

return board

def solve_util(board, row, n): if row == n: return True

for col in range(n):
    if is_safe(board, row, col, n):
        board[row][col] = 1
        if solve_util(board, row + 1, n) == True:
            return True
        board[row][col] = 0

return False

def is_safe(board, row, col, n):

for i in range(row):
    if board[i][col] == 1:
        return False

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
    if board[i][j] == 1:
        return False

for i, j in zip(range(row, -1, -1), range(col, n)):
    if board[i][j] == 1:
        return False

return True

n = 4 print(solve(n))

Output: [[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 0]] [[0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 0]]

Time Complexity: In the worst case, the algorithm visits all the positions in the board, which takes O(n^2) time. Therefore, the time complexity of the algorithm is O(n^n).

Space Complexity: The algorithm creates a board of size n^2 , which takes O(n^2) space. Therefore, the space complexity of the algorithm is O(n^2).

Therefore, the problem of finding all the positions in which n queens can be placed on the board in such a way that no two queens attack each other can be solved using backtracking.

Queens That Can Attack The King Solution Code

1