给定0和1的二进制矩阵。以行方式或列方式找出1的最长序列。 例如:
0 0 0 1 0 0
0 0 1 1 0 0
0 0 0 1 0 0
它应该返回最高计数 - 3。 帮助,在js上写这个程序
var cols = prompt("input cols", 4);
var rows = prompt("input rows", 4);
var arr = [];
for (var i = 0; i < rows; i++) {
arr[i] = [];
for (var j = 0; j < cols; j++) {
var rand = Math.round(Math.random() * 1);
arr[i][j] = rand;
}
}
console.log(arr);
var str = arr.join('\n');
console.log(str);
var List = str.split(0);
//----there is a code for continuous sequence
var max = 0;
var array = str.split('1').forEach(function (item) {
if (max < item.length) max = item.length;
})
如何按行和列搜索以查找不间断的序列
答案 0 :(得分:0)
var max_1_row = -1;
var row_num = -1
var max_1_col = -1;
var col_num = -1
for (var i = 0; i < rows; i++) {
var max_1_in_row = 0;
var max_1_in_row_seq = 0;
var max_1_in_col = 0;
var max_1_in_col_seq = 0;
for (var j = 0; j < cols; j++) {
if (arr[i][j] == 1) {
max_1_in_row += arr[i][j];
} else {
max_1_in_row = 0;
}
if (max_1_in_row > max_1_in_row_seq) {
max_1_in_row_seq = max_1_in_row;
}
//By Column
if (arr[j][i] == 1) {
max_1_in_col += arr[j][i];
} else {
max_1_in_col = 0;
}
if (max_1_in_col > max_1_in_col_seq) {
max_1_in_col_seq = max_1_in_col;
}
}
if (max_1_in_row_seq > max_1_row) {
max_1_row = max_1_in_row_seq;
row_num = i + 1;
}
if (max_1_in_col_seq > max_1_col) {
max_1_col = max_1_in_col_seq;
col_num = i + 1;
}
}
console.log(“行:”+ max_1_row +“行”+ row_num +“\ n列:”+ max_1_col +“列”+ col_num);