首页 > 解决方案 > 给定数组中的开始和结束坐标,标记数组槽以绘制矩形

问题描述

我有一个 10x10 数组,我知道矩形的起点和终点在哪里。矩形可以是 1x3、2x2、3x2 等。

给定开始和结束坐标,我需要标记矩形在 10x10 数组中的位置。

示例一(正确):

左上节点:[0, 1]

右下节点:[1, 2]

|--0--| |--x--| |--x--| |--0--|
|--0--| |--x--| |--x--| |--0--|
|--0--| |--0--| |--0--| |--0--|
|--0--| |--0--| |--0--| |--0--|

示例二(不正确):

左上节点:[1,3]

右下节点:[3,3]

电流输出:

|--0--| |--0--| |--0--| |--0--|
|--0--| |--0--| |--0--| |--x--|
|--0--| |--0--| |--0--| |--0--|
|--0--| |--0--| |--0--| |--0--|

期望的输出:

|--0--| |--0--| |--0--| |--0--|
|--0--| |--0--| |--0--| |--x--|
|--0--| |--0--| |--0--| |--x--|
|--0--| |--0--| |--0--| |--x--|

这是我尝试过的:

$width = $lowerRightNode[1] - $upperLeftNode[1] + 1;
echo 'width: ' . $width .'<br/>';
for($i=$upperLeftNode[0]; $i < $upperLeftNode[0] + $width; $i++) {
    for($z=$upperLeftNode[1]; $z <= $lowerRightNode[1]; $z++) {
        $this->_grid[$i][$z] = 'x';
        echo $i . ' ' . $z .'<br/>';
    }
}

标签: phparrays

解决方案


所以这真的很像一个洪水填充问题。您有一个固定的 2D 网格作为数组,并且您希望根据 X/Y 坐标填充特定区域。我已经简化了下面的实现来演示如何做到这一点。

const GRID_WIDTH  = 10;
const GRID_HEIGHT = 10;

// Coordinates are described as [[y1, x1], [y2, x2]]
$coordinates = [[1,3], [3,3]];

// Create the grid
$grid = array_fill(0, GRID_WIDTH, array_fill(0, GRID_HEIGHT, '-'));

// Plot the coordinates on the grid
for ($y = 0; $y < GRID_WIDTH; $y++) { // plot Y
    for ($x = 0; $x < GRID_HEIGHT; $x++) { // plot X
        if ($y >= $coordinates[0][0] && $y <= $coordinates[0][1]) {
            if ($x >= $coordinates[1][0] && $x <= $coordinates[1][1]) {
                $grid[$y][$x] = 'X';
            }
        }
    }
}

// Print the grid
foreach ($grid as $x => $y) {
    foreach ($y as $plot) {
        echo " $plot ";
    }
    echo "\n";
}

输出应该是这样的:

- - - - - - - - - -
 - - - X - - - - - -
 - - - X - - - - - -
 - - - X - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -

在您的第一个示例[0,1]中,[1,2]它看起来像这样:

- XX - - - - - - -
 - XX - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -
 - - - - - - - - - -

这里的关键是确保当我们扫描网格(从 X 到 Y)时,X1、Y1、X2 和 Y2 的坐标在光标的范围内。这允许我们一次绘制一个单元格,只要我们在这些范围内(包括在内)。这是通过检查if ($y >= $coordinates[0][0] && $y <= $coordinates[0][1])和完成的if ($x >= $coordinates[1][0] && $x <= $coordinates[1][1])。由于计算坐标的宽度是不够的(这是您上面的实现正在做的事情)。因为它没有识别高度边界。


推荐阅读