【发布时间】:2020-09-08 19:04:49
【问题描述】:
我不确定如何处理这个算法问题。
给定一个表示图像灰度的二维整数矩阵M,需要设计一个平滑器,使每个单元格的灰度变为周围所有8个单元格及其自身的平均灰度(向下取整)。如果一个单元格周围的单元格少于 8 个,则尽可能多地使用。
示例 1:
Input:
[[1, 1, 1],
[1, 0, 1],
[1, 1, 1]]
Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
解释:
对于点 (0, 0), (0, 2), (2, 0), (2, 2): floor(3 / 4) = floor(0.75) = 0
对于点 (0, 1), (1, 0), (1, 2), (2, 1): floor(5 / 6) = floor(0.83333333) = 0
对于点 (1, 1): floor(8 / 9) = floor(0.88888889) = 0
注意: 给定矩阵中的值在 [0, 255] 的范围内。 给定矩阵的长度和宽度在[1, 150]的范围内。
问题:
我的实现逻辑有问题:
我正在尝试检查所有邻居,我觉得好像我的逻辑受限,但我收到错误 Uncaught TypeError: Cannot read property '0' of undefined
到目前为止我写的代码:
const imageSmoother = (M) => {
for (let rows = 0; rows < M.length; rows++) {
for (let cols = 0; cols < M[0].length; cols++) {
let val = M[rows][cols]
let neighborsCount = 0
if (rows >= 0 && rows < M.length &&
cols >= 0 && cols < M[0].length) {
//check right
if (M[rows][cols + 1] !== undefined) {
val += M[rows][cols + 1]
neighborsCount++
}
//check left
if (M[rows][cols - 1] !== undefined) {
val += M[rows][cols - 1]
neighborsCount++
}
//check bottom
if (M[rows + 1][cols] !== undefined) {
val += M[rows + 1][cols]
neighborsCount++
}
//check above
if (M[rows - 1][cols] !== undefined) {
val += M[rows - 1][cols]
neighborsCount++
}
//check diagonal top left
if (M[rows - 1][cols - 1] !== undefined) {
val += M[rows - 1][cols - 1]
neighborsCount++
}
//check diagonal bottom right
if (M[rows + 1][cols + 1] !== undefined) {
val += M[rows + 1][cols + 1]
neighborsCount++
}
//check diagonal bottom left
if (M[rows + 1][cols - 1] !== undefined) {
val += M[rows + 1][cols - 1]
neighborsCount++
}
//check diagonal top right
if (M[rows - 1][cols + 1] !== undefined) {
val += M[rows - 1][cols + 1]
neighborsCount++
}
console.log(val, neighborsCount);
}
}
}
}
测试用例如下:
console.log(imageSmoother([[1, 1, 1],
[1, 0, 1],
[1, 1, 1]])) // [[0, 0, 0],
// [0, 0, 0],
// [0, 0, 0]]
【问题讨论】:
标签: javascript java arrays algorithm matrix