Minimum Consecutive Number in Matrix – Infytq 2019 Solve

Problem: Take a matrix as an input. Check if we get the same number consecutively at least 4 times in any fashion (Vertical, Horizontal, and Diagonal). Record those sets.

If we get multiple consecutive number then print the minimum number present in the set. If we get such no consecutive number then return -1.

Input format: The first line contains two space separated integers, the number of rows and columns. Next line contains a matrix made of given rows columns.

Sample Input:

5 6
1 3 3 3 3 9
1 6 9 2 3 9
1 2 2 5 4 9
2 2 4 5 7 9
2 4 5 6 7 2

Sample Output:

2

Explanation: So, we get [3 3 3 3] horizontally in the first line, [9 9 9 9] vertically in the last column, [2 2 2 2] diagonally. Hence, we’ll print min of 3, 9 and 2 which is 2. Hence, the output will be 2.

Solution: We strongly recommend you to try the problem first before moving to the solution.

Python

row,column=map(int,input().split(" "))
digit=[]
matrix=[]
for r in range(row):
    row_numbers=list(map(int,input().split())) 
    matrix.append(row_numbers)    
for r in range(0, row):
    for c in range(0, column):
        if(c < column-3): #condition for cosecutive numbers in all rows
        
                if(matrix[r][c]==matrix[r][c+1]==matrix[r][c+2]==matrix[r][c+3]):
                        digit.append(matrix[r][c])     
                        
        if(r < row-3):    #condition for cosecutive numbers in all columns
        
                if(matrix[r][c]==matrix[r+1][c]==matrix[r+2][c]==matrix[r+3][c]):
                        digit.append(matrix[r][c])  
                                       
        if(c < column-3 and r >= 3): #cosecutive numbers in all left to right diagonals
        
                if(matrix[r][c]==matrix[r-1][c+1]==matrix[r-2][c+2]==matrix[r-3][c+3]):            
                        digit.append(matrix[r][c])
                        
        if(c >= 3 and r >= 3):   #cosecutive numbers in all left to right diagonals
        
                if(matrix[r][c]==matrix[r-1][c-1]==matrix[r-2][c-2]==matrix[r-3][c-3]):            
                        digit.append(matrix[r][c])         
      
if(len(digit)==0):
    print("-1")
else:    
    print(min(digit))

Input:

5 6
1 3 3 3 3 9
1 6 9 2 3 9
1 2 2 5 4 9
2 2 4 5 7 9
2 4 5 6 7 2

Output:

2

Follow Us

You Missed


Leave a Comment

Your email address will not be published. Required fields are marked *