Search code examples
pythonmatrixdiagonal

Find the longest diagonal of an element in a matrix-python


I fairly new to programming, so my question may seem naive. I need a function that given a matrix like this one:

m=[['2','3','2','4','2','2','1']
   ['5','2','6','2','7','2','2']
   ['5','3','9','4','2','6','8']]

-finds the longest diagonal of the element '2' (it doesn't have to start in row one):

['2','2','2']

-outputs the position of the first element of the diagonal in the matrix:

m[0][2]

Thanks


Solution

  • result=[0,0]
    maxdiag = 0
    for i in range (0, len(m)):
      for j in range (0, len(m[i])):
        k = 0;
        while (i+k < len(m) and j+k < len(m[0]) and m[i+k][j+k] == '2'):
          k+=1;
          if (k > maxdiag):
            maxdiag = k;
            result[0]=i;
            result[1]=j;
    

    Coordinates are stored in result.

    This is, in my opinion, the empirical solution.

    Iterate over the matrix, and when you find a '2', iterate "diagonally" adding the iterator k to i and j (for example, if you find a '2' on m[1][1] your loop iterates on m[2][2], m[3][3], etc...), and when you find a higher diagonal than the current one, replace the coordinates in the result (sorry for my bad english).