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.

这道题给了我们一个二维矩阵,让我们求矩阵中最长的连续1,连续方向任意,可以是水平,竖直,对角线或者逆对角线均可。那么最直接最暴力的方法就是四个方向分别来统计最长的连续1,其中水平方向和竖直方向都比较容易,就是逐行逐列的扫描,使用一个计数器,如果当前位置是1,则计数器自增1,并且更新结果res,否则计数器清零。对于对角线和逆对角线需要进行些坐标转换,对于一个mxn的矩阵,对角线和逆对角线的排数都是m+n-1个,难点在于我们要确定每一排上的数字的坐标,如果i是从0到m+n-1之间遍历,j是在i到0之间遍历,那么对角线的数字的坐标就为(i-j, j),逆对角线的坐标就为(m-1-i+j, j),这是博主千辛万苦试出来的T.T,如果能直接记住,效果肯定棒!那么有了坐标转换,求对角线和逆对角线的连续1也就不是啥难事了,参见代码如下:

解法一:

class Solution {
public:
int longestLine(vector<vector<int>>& M) {
if (M.empty() || M[].empty()) return ;
int res = , m = M.size(), n = M[].size();
for (int i = ; i < m; ++i) { // Check horizontal
int cnt = ;
for (int j = ; j < n; ++j) {
if (M[i][j] == ) res = max(res, ++cnt);
else cnt = ;
}
}
for (int j = ; j < n; ++j) {
int cnt = ;
for (int i = ; i < m; ++i) { // Check vertical
if (M[i][j] == ) res = max(res, ++cnt);
else cnt = ;
}
}
for (int i = ; i < m + n - ; ++i) {
int cnt1 = , cnt2 = ;
for (int j = i; j >= ; --j) {
if (i - j < m && j < n) { // Check diagonal
if (M[i - j][j] == ) res = max(res, ++cnt1);
else cnt1 = ;
}
int t = m - - i + j;
if (t >= && t < m && j < n ) { // Check anti-diagonal
if(M[t][j] == ) res = max(res, ++cnt2);
else cnt2 = ;
}
}
}
return res;
}
};

如果上面的解法的坐标转换不好想的话,我们也可以考虑用DP解法来做,我们建立一个三维dp数组,其中dp[i][j][k]表示从开头遍历到数字nums[i][j]为止,第k种情况的连续1的个数,k的值为0,1,2,3,分别对应水平,竖直,对角线和逆对角线这四种情况。之后就是更新dp数组的过程了,如果如果数字为0的情况直接跳过,然后水平方向就加上前一个的dp值,竖直方向加上上面一个数字的dp值,对角线方向就加上右上方数字的dp值,逆对角线就加上左上方数字的dp值,然后每个值都用来更新结果res,参见代码如下:

解法二:

class Solution {
public:
int longestLine(vector<vector<int>>& M) {
if (M.empty() || M[].empty()) return ;
int m = M.size(), n = M[].size(), res = ;
vector<vector<vector<int>>> dp(m, vector<vector<int>>(n, vector<int>()));
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (M[i][j] == ) continue;
for (int k = ; k < ; ++k) dp[i][j][k] = ;
if (j > ) dp[i][j][] += dp[i][j - ][]; // horizonal
if (i > ) dp[i][j][] += dp[i - ][j][]; // vertical
if (i > && j < n - ) dp[i][j][] += dp[i - ][j + ][]; // diagonal
if (i > && j > ) dp[i][j][] += dp[i - ][j - ][]; // anti-diagonal
res = max(res, max(dp[i][j][], dp[i][j][]));
res = max(res, max(dp[i][j][], dp[i][j][]));
}
}
return res;
}
};

下面我们来优化空间复杂度,用一种类似于DFS的思路来解决问题,我们在遍历到为1的点时,对其水平方向,竖直方向,对角线方向和逆对角线方向分别不停遍历,直到越界或者遇到为0的数字,同时用计数器来累计1的个数,这样就可以用来更新结果res了,就不用把每个中间结果都保存下来了,参见代码如下:

解法三:

class Solution {
public:
int longestLine(vector<vector<int>>& M) {
if (M.empty() || M[].empty()) return ;
int m = M.size(), n = M[].size(), res = ;
vector<vector<int>> dirs{{,},{,},{-,-},{-,}};
for (int i = ; i < m; ++i) {
for (int j = ; j < n; ++j) {
if (M[i][j] == ) continue;
for (int k = ; k < ; ++k) {
int cnt = , x = i, y = j;
while (x >= && x < m && y >= && y < n && M[x][y] == ) {
x += dirs[k][];
y += dirs[k][];
++cnt;
}
res = max(res, cnt);
}
}
}
return res;
}
};

参考资料:

https://discuss.leetcode.com/topic/87231/dfs-straightforward

https://discuss.leetcode.com/topic/87197/java-o-nm-time-dp-solution

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Longest Line of Consecutive One in Matrix 矩阵中最长的连续1的更多相关文章

  1. LC 562. Longest Line of Consecutive One in Matrix

    Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horiz ...

  2. LeetCode 562. Longest Line of Consecutive One in Matrix(在矩阵中最长的连续1)$

    Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be horiz ...

  3. Longest Line of Consecutive One in Matrix

    Given a 01 matrix, find the longest line of consecutive 1 in the matrix. The line could be horizonta ...

  4. [LeetCode] Longest Increasing Path in a Matrix 矩阵中的最长递增路径

    Given an integer matrix, find the length of the longest increasing path. From each cell, you can eit ...

  5. 329 Longest Increasing Path in a Matrix 矩阵中的最长递增路径

    Given an integer matrix, find the length of the longest increasing path.From each cell, you can eith ...

  6. LeetCode All in One题解汇总(持续更新中...)

    突然很想刷刷题,LeetCode是一个不错的选择,忽略了输入输出,更好的突出了算法,省去了不少时间. dalao们发现了任何错误,或是代码无法通过,或是有更好的解法,或是有任何疑问和建议的话,可以在对 ...

  7. [Leetcode] Longest consecutive sequence 最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  8. [LeetCode] Longest Consecutive Sequence 求最长连续序列

    Given an unsorted array of integers, find the length of the longest consecutive elements sequence. F ...

  9. LeetCode——Longest Consecutive Sequence

    LeetCode--Longest Consecutive Sequence Question Given an unsorted array of integers, find the length ...

随机推荐

  1. Java多线程:线程池

    一. 背景 线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,合理的使用线程池可以对线程进行统一的分配.调优和监控,并有以下好处:     第一:降低资源消耗.通过重复利用已 ...

  2. kill-mysql-sleep.sh

    #!/bin/bash #while : #do n=`/usr/bin/mysqladmin -uroot -pXXXXX processlist | grep -i sleep | wc -l` ...

  3. KVM之十一:调整cpu和内存

    1.virsh edit snale (更改前要将snale shutdown) 找到"memory"和"vcpu"标签,将 <memory unit=' ...

  4. js网页判断移动终端浏览器版本信息是安卓还是苹果ios,判断在微信浏览器跳转不同页面,生成二维码

    一个二维码,扫描进入网页,自动识别下载苹果和安卓客户端,判断网页如下,(只有苹果的微信不能自动跳转)所以加个微信判断. <!DOCTYPE html> <html> <h ...

  5. java多线程的(一)-之java线程的使用

    一.摘要 每天都和电脑打交道,也相信大家使用过资源管理器杀掉过进程.而windows本身就是多进程的操作系统 在这里我们理解两组基本概念: 1.进程和线程的区别???? 2.并行与并发的区别???? ...

  6. Leetcode 24——Swap Nodes in Pairs

    Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2-& ...

  7. Mysql数据库的触发程序

    /** **创建表 */ CREATE TABLE test1(a1 INT); CREATE TABLE test2(a2 INT); CREATE TABLE test3(a3 INT NOT N ...

  8. a标签传递参数

    a标签传递参数 单个参数:参数名称前面跟   ? <a href="localhost:8080/arguments?id=1">单个参数</a> 多个参数 ...

  9. EasyUI中, datagrid用loadData方法绑定数据。

    $("#dg").datagrid("loadData", { , " }, { "ck": "1", &qu ...

  10. 剑指offer-数据流中的中位数

    题目描述 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值.如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值.   ...