LeetCode 562. Longest Line of Consecutive One in Matrix(java)

Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horizontal, vertical, diagonal or anti-diagonal.

Example:
Input:
[[0,1,1,0],
 [0,1,1,0],
 [0,0,0,1]]
Output: 3

Hint: The number of elements in the given matrix will not exceed 10,000.

递归的解法,同时maintain一个最大值,注意8个方向中只需要走4个方向即可。
public class Solution {
    int [][] directions = new int[][]{{1,0},{0,1},{1,1},{1,-1}};
    public int longestLine(int[][] M) {
        if(M == null || M.length == 0 || M[0].length == 0) return 0;
        int res = 0;
        for(int i =0; i < M.length; i++){
            for(int j = 0;j < M[0].length; j++){
                if(M[i][j] == 1){
                    res = Math.max(res,getMax(M, i, j));
                }
            }
        }
        return res;
    }
    private int getMax(int [][] M, int x, int y){
        int res = 1;
        for(int [] dir : directions){
            int i = x + dir[0];
            int j = y + dir[1];
            int count = 1;
            while(i< M.length && j< M[0].length && i >= 0 && j >= 0 && M[i][j] == 1){
                i += dir[0];
                j += dir[1];
                count++;
            }
            res = Math.max(count,res);
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值