面试问题 - 寻找坐标二维数组

Interview prob - finding coordinates 2d array

  var image = [
  [1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 0, 0, 0, 1],
  [1, 1, 1, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1]
];

有一个每个像素都是 white/black 的图像。图像是一个简单的二维数组(0 = 黑色,1 = 白色)。已知您获得的图像在白色背景上有一个黑色矩形。您的目标是找到这个矩形和 return 它的坐标。

如何遍历一个二维数组?

var image = [
  [1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 0, 0, 0, 1],
  [1, 1, 1, 0, 0, 0, 1],
  [1, 1, 1, 1, 1, 1, 1]
];

for (var i = 0; i < image.length; i++) {
    // row is a 1D array
    var row = image[i];
}

第一个索引将 return 第一行,依此类推。

随后,您可以像访问普通 (1D) 数组一样访问行中的每个像素。

我不确定您是只需要知道左上角的坐标,还是还需要知道矩形的宽度和高度。我会将两者都包含在我的回答中。

要找到左上角,我会使用以下函数:

function findTopLeftCorner(image) {
    var imageHeight = image[0].length; // Assuming all columns have the same height
    // All columns should have the same height because it is an image
    var imageWidth = image.length;
    for (var x = 0; x < imageWidth; x++) {
        for (var y = 0; y < imageHeight; y++) {
            if (image[x][y] == 0) {
                return {x: x, y: y};
            }
        }
    }
}

要找到宽度和高度,我会使用以下函数:

function getWidthOfRectangle(image, topLeftCorner) {
    var x = topLeftCorner.x;
    while (image[x][topLeftCorner.y] == 0) {
        x++;
    }
    //Now x is the x-coordinate of the first white (1) pixel found
    //Therefore subtract 1 from it to find the last black (0) pixel found
    x--;
    return x - topLeftCorner.x;
}

function getHeightOfRectangle(image, topLeftCorner) {
    var y = topLeftCorner.y;
    while (image[topLeftCorner.x][y] == 0) {
        y++;
    }
    //Now y is the y-coordinate of the first white (1) pixel found
    //Therefore subtract 1 from it to find the last black (0) pixel found
    y--;
    return y - topLeftCorner.y;
}

综合起来:

var topLeftCorner = findTopLeftCorner(image);
var rectangle = {
                 x: topLeftCorner.x,
                 y: topLeftCorner.y,
                 width: getWidthOfRectangle(image, topLeftCorner),
                 height: getHeightOfRectangle(image, topLeftCorner)
};

希望这对您有所帮助。这是我的第一个回答,所以如果我有错误,请随时在评论中告诉我。

我已经提供了解决方案。 基本上你需要找出这个二维数组的长度。 Get size of dimensions in array

然后从第一个元素开始遍历,直到找到矩形左上角的第一个零元素。

for(i=0;i<dim[0];i++)
           for(j=0;j<dim[1];j++){
               if(!image[i][j]) {
                     document.getElementById('top-left').innerHTML = i+' '+j;
                        return;
       }
    }

同样从最后一个元素开始遍历,找到第一个零元素即矩形的右下角坐标

https://jsfiddle.net/wdwgmczr/2/

只需完成这个 fiddle。进行一些更改,请参阅 output.Hope 它会有所帮助。