Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the maximum sum of squares of two non-attacking rooks placed on a matrix?

There is a m x n matrix given each with integer elements. The problem says that we have to place two rooks on that matrix, such that they don't attack each other and the sum of the elements on which the rooks are placed is maximum.

Example: Let's say matrix is

2 5
1 3

Then non-attacking rooks can be placed only on 2,3 or 1,5 element positions. But the maximum sum is found in case of 1,5, so the function should return 1 + 5 = 6.

I thought that we could go through all the pairs of the array one by one and then return the maximum sum that we found, but I can't seem to find a better or efficient approach for this. My solution would be O(m * m * n * n) in terms of complexity.

What would be a better approach? I would appreciate any help.

like image 594
Panda Avatar asked Nov 13 '20 04:11

Panda


People also ask

What is the largest number of non-attacking rooks one can place on Nxn chess board?

A precursor to the rook polynomial is the classic "Eight rooks problem" by H. E. Dudeney in which he shows that the maximum number of non-attacking rooks on a chessboard is eight by placing them on one of the main diagonals (Fig. 1).

How many ways can you place 2 rooks on a chessboard such that they are not in attacking positions?

In how many ways can you place 2 rooks on a chessboard such that they are not in attacking positions? The second rook cannot be placed in the same row or the same column. So, it has 7 rows and 7 columns left for it. It can be placed in 49 ways.

How many ways are there to place 2 identical rooks in a common row or column of an 8x8 chess board?

Solved Examples. Example 1: In how many ways can you place 2 rooks on 8*8 chessboard such that they are not in attacking positions? Therefore, total number of ways= 64*7*7/2= 32*49=1568.


Video Answer


1 Answers

  1. For each row, find the top 2 values and remember the column where they were found. O(mn)

  2. For each column, find the top 2 values and remember the row where they were found. O(mn)

  3. The the remaining operations, we only use the two lists built above. We will not look at the matrix again:

    1. For each row, pretend to place a rook in that row and in the column with the highest value. For each column, sum that top value with the top value for the column, except for the column where the rook is, where we sum with the second highest value. Remember the row of the pretend rook and the column with the highest sum. O(mn)

    2. Repeat, but use the second highest value. O(mn)

Operation complete. O(mn) + O(mn) + O(mn) + O(mn) = O(mn)

like image 190
Andreas Avatar answered Sep 20 '22 18:09

Andreas