O(mn) runtime, O(m+n) space


  • 0
    public class Solution {
        public int LongestLine(int[,] M) {
            int rows = M.GetLength(0);
            int cols = M.GetLength(1);
            int maxFound = 0;
            int[] rc = new int[rows], cc = new int[cols], dd = new int[rows+cols], ad = new int[rows + cols];
            for(int i = 0; i < rows; i++)
            {
                for(int j = 0; j < cols; j++)
                {
                    if (M[i, j] == 0)
                    {
                        rc[i] = 0;
                        cc[j] = 0;
                        dd[i + j] = 0;
                        ad[j-i+rows-1] = 0;
                        
                    }
                    else {
                        rc[i] = (j-1 >= 0 && M[i, j-1] == 1) ? rc[i] + 1 : 1;
                        cc[j] = (i-1 >= 0 && M[i-1, j] == 1) ? cc[j] + 1 : 1;
                        dd[i+j] = (i-1 >= 0 && j + 1 < cols && M[i-1, j+1] == 1) ? dd[i+j] + 1 : 1;
                        ad[j-i+rows-1] = (i-1 >= 0 && j-1 >= 0 && M[i-1, j-1] == 1) ? ad[j-i+rows-1] + 1 : 1;
                    }
                    
                    maxFound = Math.Max(maxFound, Math.Max(Math.Max(rc[i],cc[j]), Math.Max(dd[i+j], ad[j-i+rows-1])));
                }
            }
            
            return maxFound;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.