Program to find number of ways to arrange n rooks so that they cannot attack each other in Python

Suppose we have a number n representing a chessboard of size n x n. We have to find the number of ways we can place n rooks, such that they cannot attack each other. Here two ways will be considered different if in one of the ways, some cell of the chessboard is occupied, and another way, the cell is not occupied. (We know that rooks can attack each other if they are either on the same row or on the same column).

So, if the input is like 3, then the output will be 6.

3x3 Chessboard - Non-attacking Rook Arrangements ? ? ? Way 1 ? ? ? Way 2 ? ? ? Way 3 ... and 3 more ways (total = 3! = 6) Each row and column has exactly one rook

Understanding the Problem

To place n rooks on an n×n chessboard such that they don't attack each other, each rook must be in a different row and different column. This is equivalent to finding the number of permutations of n items, which is n! (n factorial).

Algorithm

The solution involves these steps ?

  • Calculate the factorial of n
  • Return the factorial value

Implementation

import math

class Solution:
    def solve(self, n):
        return math.factorial(n)

ob = Solution()
print(ob.solve(3))

The output of the above code is ?

6

Alternative Implementation

We can also calculate factorial manually without using the math library ?

class Solution:
    def solve(self, n):
        factorial = 1
        for i in range(1, n + 1):
            factorial *= i
        return factorial

ob = Solution()
print(f"Ways to arrange {3} rooks: {ob.solve(3)}")
print(f"Ways to arrange {4} rooks: {ob.solve(4)}")

The output of the above code is ?

Ways to arrange 3 rooks: 6
Ways to arrange 4 rooks: 24

How It Works

For an n×n board with n rooks:

  • The first rook can be placed in any of the n columns of the first row
  • The second rook can be placed in any of the remaining (n-1) columns of the second row
  • The third rook can be placed in any of the remaining (n-2) columns of the third row
  • And so on...

This gives us n × (n-1) × (n-2) × ... × 1 = n! total arrangements.

Conclusion

The number of ways to arrange n rooks on an n×n chessboard so they cannot attack each other is simply n factorial. This is because each arrangement corresponds to a unique permutation of column positions for each row.

Updated on: 2026-03-25T10:55:08+05:30

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements