我想执行特定类型的搜索。我不知道它是否有名称,但我可以描述它,并有执行它的工作代码。
对于二维矩阵,从点 0,0 开始并向右下方工作,搜索生成将如下所示:
- 1、 4、 9、16、...
- 2、 3、 8、15、...
- 5、 6、 7、14、...
- 10、11、12、13、...
- ...
因此,第一个搜索循环将检查 1,第二个循环将检查 2、3、4,第三个循环将检查 5、6、7、8、9 等。
产生此搜索的代码是:
$row_search = 0;
$point_not_found = true;
while ($point_not_found && $row_search < $matrix_height/2)
{
$current = array(0, $row_search);
while ($current[0] < $row_search)
{
if (searchForPoint( $matrix, $current ) !== false)
$point_not_found = false;
++$current[0];
}
if (!$anchor_not_found)
break;
while ($current[1] >= 0)
{
if (searchForPoint( $matrix, $current ) !== false)
$point_not_found = false;
--$current[1];
}
++$row_search;
}
我对搜索被分成两个循环的方式不满意,因为循环内的代码几乎相同。您能否建议一种组合或嵌套循环并消除对 searchForPoint 的冗余调用的方法?
最佳答案
这样的事情怎么样
$pointFound = false;
$row = 0;
while(!$pointFound && $row < $matrixSize)
{
$y = $row;
$x = 0;
while($y >= 0)
{
if (searchForPoint($matrix,$x,$y) !== false)
{
$pointFound = true;
break;
}
// If we reached the right column, start moving upwards (decreasing y)
if($x == $row)
$y--;
// Else move right
else
$x++;
}
// EDIT (forgot the next line)
$row++;
}
关于php - 组合算法中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4878160/