You must Sign In to post a response.
  • Category: .NET

    Find the longest sequence in a matrix

    Hi,
    I have a problem related to a matrix of 6*7 as below
    0 0 0 0 0 0 0
    1 0 1 0 1 1 1
    0 0 0 1 0 0 0
    0 1 0 0 0 0 0
    0 0 0 0 0 0 0
    1 1 1 1 1 1 1

    In above matrix on some position there is 1 and on some position 0 is mentioned. Total position containing 1 is 14.
    I need to get the longest sequence of 1 in a horizontal/vertical/diagonal way.
    Please help me to solve this problem.

    Program should return answer 7(last bottom row containing longest sequence of 1).

    Thanks
    Anil
  • #765861
    Hi Anil,

    You can write different loops for rows and columns -

    int cntOne(int row, int col)
    {
    // assuming a[][] contains the given matrix
    int ans = -1;

    for (int i = 0; i < row; ++i)
    {
    for (int j = 1; j < col; ++j)
    {
    if(a[i][j] == 1)
    d[i][j] = 1 + d[i - 1][j];
    ans = max(ans, d[i][j]);
    }
    }

    for (int j = 0; j < col; ++j)
    {
    for (int i = 1; i < row; ++i)
    {
    if(a[i][j] == 1)
    d[i][j] = 1 + d[i][j - 1];
    ans = max(ans, d[i][j]);
    }
    }
    return ans;
    }

    Hope it helps!!


  • Sign In to post your comments