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.
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).
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.
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.
For each row, find the top 2 values and remember the column where they were found. O(mn)
For each column, find the top 2 values and remember the row where they were found. O(mn)
The the remaining operations, we only use the two lists built above. We will not look at the matrix again:
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)
Repeat, but use the second highest value. O(mn)
Operation complete. O(mn) + O(mn) + O(mn) + O(mn) = O(mn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With