Program to find out the cells containing maximum value in a matrix in Python

PythonServer Side ProgrammingProgramming

Suppose, there is a n x n matrix initialized with 0s. Now, a list is given and it contains some pairs that contain a particular row and a column position. For each item i in the list, the contents of the cells increase by 1 where the row number and the column number are less than the row value and column value of item i in the list. After all the list elements have been traversed, we have to find out the number of cells in the matrix that contains the maximum value. (row and column index start at 0)

So, if the input is like input_list = [[3, 5], [4, 6], [5, 3]], then the output will be 9.Suppose, it is a 5 x 6 matrix. At first the values in the matrix are

0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

After the first element of the list have been traversed, it becomes −

1 1 1 1 1 0
1 1 1 1 1 0
1 1 1 1 1 0
0 0 0 0 0 0
0 0 0 0 0 0

After the second element of the list have been traversed, it becomes −

2 2 2 2 2 1
2 2 2 2 2 1
2 2 2 2 2 1
1 1 1 1 1 1
0 0 0 0 0 0

After the third element of the list has been traversed, it becomes −

3 3 3 2 2 1
3 3 3 2 2 1
3 3 3 2 2 1
2 2 2 1 1 1
1 1 1 0 0 0

The maximum value in the matrix is 3, and there are 9 cells that contain the value.

To solve this, we will follow these steps

  • xpos := 0
  • ypos := 0
  • for each item in input_list, do
    • if xpos is same as 0, then
      • xpos := item[0]
      • ypos := item[1]
    • otherwise,
      • xpos := minimum of (xpos, item[0])
      • ypos := minimum of (ypos, item[1])
  • return(xpos * ypos)

Example

Let us see the following implementation to get better understanding −

def solve(input_list):
   xpos = 0
   ypos = 0
   for item in input_list:
      if xpos == 0:
         xpos = item[0]
         ypos = item[1]
      else:
         xpos = min(xpos,item[0])
         ypos = min(ypos,item[1])
   return (xpos * ypos)

print(solve([[3, 5], [4, 6], [5, 3]]))

Input

[[3, 5], [4, 6], [5, 3]]

Output

9
raja
Published on 23-Oct-2021 07:58:07
Advertisements