PHP 沙漏图案(Hour-glass Pattern)
给定正整数 n,以沙漏形式打印数字模式。
示例:
输入:rows_no = 7
输出:
1 2 3 4 5 6 7
2 3 4 5 6 7
3 4 5 6 7
4 5 6 7
5 6 7
6 7
7
6 7
5 6 7
4 5 6 7
3 4 5 6 7
2 3 4 5 6 7
1 2 3 4 5 6 7
<?php
// PHP code for hour glass pattern
// Function definition
function pattern($rows_no)
{
// for loop for printing
// upper half
for ($i = 1; $i <= $rows_no; $i++)
{
// printing i spaces at
// the beginning of each row
for ($k = 1; $k < $i; $k++)
echo " ";
// printing i to rows value
// at the end of each row
for ($j = $i; $j <= $rows_no; $j++)
echo $j." ";
echo "\n";
}
// for loop for printing lower half
for ($i = $rows_no - 1; $i >= 1; $i--)
{
// printing i spaces at the
// beginning of each row
for ($k = 1; $k < $i; $k++)
echo " ";
// printing i to rows value
// at the end of each row
for ($j = $i; $j <= $rows_no; $j++)
echo $j." ";
echo "\n";
}
}
// Driver code
$rows_no = 7;
pattern($rows_no);
// This code is contributed by mits
?>
输出 :
1 2 3 4 5 6 7
2 3 4 5 6 7
3 4 5 6 7
4 5 6 7
5 6 7
6 7
7
6 7
5 6 7
4 5 6 7
3 4 5 6 7
2 3 4 5 6 7
1 2 3 4 5 6 7
时间复杂度: O(rows_no*rows_no),其中rows_no是从用户获取的行值。
空间复杂度: O(1),因为我们不使用任何额外的空间。
原文地址:https://blog.csdn.net/hefeng_aspnet/article/details/140601801
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!