尋找 JavaScript 中矩陣中 1 的最長行
假設我們有一個二進位制矩陣(一個僅包含 0 或 1 的陣列陣列),如下所示 -
const arr = [ [0,1,1,0], [0,1,1,0], [0,0,0,1] ];
我們需要編寫一個 JavaScript 函式,該函式接收一個這樣的矩陣作為第一個也是唯一的引數。
我們的函式的任務是找到矩陣中最長的連續 1 行,並返回其中的 1 的數量。該行可以是水平的、垂直的、對角線的或反對角線的。
例如,對於以上陣列,輸出應該是 -
const output = 3
因為最長的行是從 arr[0][1] 開始並對角線跨越到 -
arr[2][3]
示例
程式碼如下 -
const arr = [
[0,1,1,0],
[0,1,1,0],
[0,0,0,1]
];
const longestLine = (arr = []) => {
if(!arr.length){
return 0;
}
let rows = arr.length, cols = arr[0].length;
let res = 0;
const dp = Array(rows).fill([]);
dp.forEach((el, ind) => {
dp[ind] = Array(cols).fill([]);
dp[ind].forEach((undefined, subInd) => {
dp[ind][subInd] = Array(4).fill(null);
});
});
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (arr[i][j] == 1) {
dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;
dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;
dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;
dp[i][j][3] = (i > 0 && j < cols - 1) ? dp[i - 1][j + 1][3] + 1 : 1;
res = Math.max(res, Math.max(dp[i][j][0], dp[i][j][1]));
res = Math.max(res, Math.max(dp[i][j][2], dp[i][j][3]));
};
};
};
return res;
};
console.log(longestLine(arr));輸出
控制檯中的輸出將為 -
3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP