本内容分享了利用PHP语言完成顺时针方向打印矩阵的操作技巧,供读者参考借鉴。
顺时针打印矩阵的问题描述与解决思路
问题描述
给定一个二维矩阵作为输入,要求遵循从外圈向内圈、顺时针旋转的路径,逐个提取并输出其中的数值。假设输入的矩阵结构如下所示:
| 1 | 2 | 3 | 4 |
| 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 |
对应的输出序列应为:1, 2, 3, 4, 8, 12, 16, 15, 14, 13, 9, 5, 6, 7, 11, 10。
解决策略
主要采用分层剥离的方式,即一圈一圈地向外围推进。关键在于合理设定和更新循环的边界条件。此外,必须妥善处理矩阵仅有一行或仅有一列时的特殊逻辑分支。
代码实现
<?php
function printMatrix($matrix)
{
$row = count($matrix);
$col = count($matrix[0]);
if($row == 0 || $col == 0)
return $matrix;
$result = array();
$left = 0;$right = $col-1; $top = 0;$bottom = $row-1;
while($left<=$right && $top<= $bottom){
for($i =$left;$i<=$right;++$i){
array_push($result, $matrix[$top][$i]);
}
for($i =$top+1;$i<=$bottom;++$i)
array_push($result, $matrix[$i][$right]);
if($top!=$bottom){
for($i = $right-1;$i>=$left;--$i)
array_push($result, $matrix[$bottom][$i]);
}
if($left!=$right){
for($i = $bottom-1;$i>$top;--$i)
array_push($result, $matrix[$i][$left]);
}
$left++;$right--;$top++;$bottom--;
}
return $result;
}
期望上述内容能对各位的PHP编程学习提供有益的帮助。