php怎么实现二维数组旋转
编程狂想曲
2024-04-25 17:57
短信预约 PHP-IT技能 免费直播动态提醒
这篇文章将为大家详细讲解有关php怎么实现二维数组旋转,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
什么是二维数组旋转?
二维数组旋转是指将二维数组中的元素按顺时针或逆时针方向进行旋转 90 度或 180 度。
实现二维数组旋转的方法
以下介绍两种实现二维数组旋转的方法:
方法 1:使用四层循环(适用于 90 度旋转)
function rotateArray90(array $array) {
$rows = count($array);
$cols = count($array[0]);
$rotatedArray = array_fill(0, $cols, array_fill(0, $rows, 0));
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$rotatedArray[$j][$rows - $i - 1] = $array[$i][$j];
}
}
return $rotatedArray;
}
方法 2:使用数组切片语法(适用于 90 度或 180 度旋转)
function rotateArray(array $array, $degrees) {
$rows = count($array);
$cols = count($array[0]);
$rotatedArray = array_fill(0, $cols, array_fill(0, $rows, 0));
switch ($degrees) {
case 90:
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$rotatedArray[$j][$rows - $i - 1] = $array[$i][$j];
}
}
break;
case 180:
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
$rotatedArray[$rows - $i - 1][$cols - $j - 1] = $array[$i][$j];
}
}
break;
default:
throw new InvalidArgumentException("Invalid rotation angle: $degrees");
}
return $rotatedArray;
}
示例用法
$array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$rotatedArray90 = rotateArray90($array);
// 输出:
// [
// [7, 4, 1],
// [8, 5, 2],
// [9, 6, 3]
// ]
$rotatedArray180 = rotateArray($array, 180);
// 输出:
// [
// [9, 8, 7],
// [6, 5, 4],
// [3, 2, 1]
// ]
以上就是php怎么实现二维数组旋转的详细内容,更多请关注编程学习网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341