算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 矩阵中最长的连续1线段,我们先来看题面:
https://leetcode-cn.com/problems/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 horizontal, vertical, diagonal or anti-diagonal.
给定一个01矩阵 M,找到矩阵中最长的连续1线段。这条线段可以是水平的、垂直的、对角线的或者反对角线的。
示例
输入:
[[0,1,1,0],
[0,1,1,0],
[0,0,0,1]]
输出: 3
提示: 给定矩阵中的元素数量不会超过 10,000。
解题
https://blog.csdn.net/weixin_44171872/article/details/108948789
使用动态规格
class Solution {
public:
int longestLine(vector<vector<int>>& M) {
if(M.empty()||M[0].empty()){//处理特殊的情形
return 0;
}
//矩阵的行和列
int len_row=M.size();
int len_col=M[0].size();
//动态数组,分别保存行,列,对角线和反对角线上的当前元素下连续1的个数
vector<int> rows(len_col,0);
vector<int> cols(len_col,0);
vector<int> dia(len_col,0);
vector<int> rev_dia(len_col,0);
int res=0;//保存中间出现过的最长的长度
//遍历数组元素
for(int i=0;i<len_row;++i){
int pre=dia[0];//辅助对角线数组数组,初始值置为对角线数组的首元素
for(int j=0;j<len_col;++j){
if(M[i][j]==1){//元素为1时,更新可能的最长的长度
rows[j]=j>0?rows[j-1]+1:1;//行
cols[j]=i>0?cols[j]+1:1;//列
//对角线
int tmp=dia[j];
dia[j]=i>0&&j>0?pre+1:1;
pre=tmp;
//反对角线
rev_dia[j]=i>0&&j<len_col-1?rev_dia[j+1]+1:1;
//更新可能的最大值
res=max(res,rows[j]);
res=max(res,cols[j]);
res=max(res,dia[j]);
res=max(res,rev_dia[j]);
}
else{
//更新元素值为0
rows[j]=0;
cols[j]=0;
pre=dia[j];
dia[j]=0;
rev_dia[j]=0;
}
}
}
return res;//返回结果
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: