给出一个0和1的二元矩阵查找1的最长序列(按行或按列)。
0 0 0 1 0 0
0 0 1 1 0 0
0 0 0 1 0 0
它应该返回最高计数–3。帮助请用Java编写这个程序我写了一个简单的算法,但它没有考虑序列。
public int columnMaxSequence(int[][] matrix) {
int maxSequence = 0;
int max = 0;
for (int i = 0; i < matrix[0].length; i++) {
for (int j = 0; j < matrix.length; j++) {
if (matrix[j][i] == 1) {
max++;
}
}
if (max > maxSequence) {
maxSequence = max;
}
max = 0;
}
return maxSequence;
}
public int rowMaxSequence(int[][] matrix) {
int maxSequence = 0;
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == 1) {
max++;
}
}
if (max > maxSequence) {
maxSequence = max;
}
max = 0;
}
return maxSequence;
}
/*
Returns the maximum sequence of 1s in a matrix.
*/
public int maxSequence(int[][] matrix) {
int rowMaxSequence = rowMaxSequence(matrix);
int columnMaxSequence = columnMaxSequence(matrix);
if (rowMaxSequence >= columnMaxSequence) {
return rowMaxSequence;
} else {
return columnMaxSequence;
}
}
最佳答案
你应该试试这个:
void main(int[][] matrix)
{
System.out.println(Math.max(columnMaxSequence(matrix), rowMaxSequence(matrix)));
}
public int columnMaxSequence(int[][] matrix)
{
int max = 0;
for(int i = 0; i < matrix[0].length; i++) // Column Index
{
int tempMax = 0;
for(int j = 0; j < matrix.length; j++) // Row Index
{
if(matrix[j][i] == 1)
{
tempMax = 1;
for(int k = j+1; k < matrix.length; k++)
{
if(matrix[k][i] == 1)
tempMax++;
else break;
}
if(max < tempMax)
max = tempMax;
}
}
}
return max;
}
public int rowMaxSequence(int[][] matrix)
{
int max = 0;
for(int i = 0; i < matrix.length; i++)
{
int tempMax = 0;
for(int j = 0; j < matrix[0].length; j++)
{
if(matrix[i][j] == 1)
{
tempMax = 1;
for(int k = j+1; k < matrix[0].length; k++)
{
if(matrix[i][k] == 1)
tempMax++;
else break;
}
if(max < tempMax)
max = tempMax;
}
}
}
return max;
}
解释-
对于rowMaxSequence():
循环沿着矩阵向下,并且
i
存储每行索引的值j
将每个元素的索引存储在i
行中在(i, j)
处,如果矩阵找到1,则计算该行中1的个数,直到找到0,然后断开它以同样的方式不断地检查那一行,当orw完成时,它将下一行。对于columnMaxSequence():
循环向右穿过矩阵,
i
是当前列的索引j
是该列中的元素。如果(j, i)
是1,那么它会计算1在它下面,直到找到0为止然后就断了。它一直以这种方式检查列,并继续向右列移动。