Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tìm đường chéo dài nhất của 1 trong ma trận bằng JavaScript


Cho ma trận nhị phân (chỉ chứa 0, 1). Cần viết hàm JS nhận ma trận, tìm đường liên tiếp của 1 dài nhất (ngang, dọc, chéo, chéo ngược) và trả về số lượng 1.

Ví dụ:

const arr = [    [0,1,1,0],    [0,1,1,0],    [0,0,0,1] ];

Kết quả:

const output = 3

đường chéo dài nhất bắt đầu từ arr[0][1] đến arr[2][3].

Ví dụ

Mã thực hiện:

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));

Kết quả

Kết quả in ra console:

3