Short and simple C++ and Python

  • 0

    I just go through the matrix and my len keeps track of the current 1-line lengths. Rows, columns, diagonals and anti-diagonals are identified by i, j, i+j and i-j, respectively. To distinguish the different directions, I add different fractions.


    int longestLine(vector<vector<int>>& M) {
        int maxlen = 0;
        map<float, int> len;
        for (int i = 0; i < M.size(); i++)
            for (int j = 0; j < M[i].size(); j++)
                for (float key : (float[]){i, j+.1, i+j+.2, i-j+.3})
                    maxlen = max(maxlen, ++len[key] *= M[i][j]);
        return maxlen;


    def longestLine(self, M):
        maxlen = 0
        currlen = collections.Counter()
        for i, row in enumerate(M):
            for j, a in enumerate(row):
                for key in i, j+.1, i+j+.2, i-j+.3:
                    currlen[key] = (currlen[key] + 1) * a
                    maxlen = max(maxlen, currlen[key])
        return maxlen

Log in to reply

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