Home >Backend Development >PHP Tutorial > 今天遇到的一份面试题

今天遇到的一份面试题

WBOY
WBOYOriginal
2016-06-13 13:43:01873browse

今天遇到的一份面试题,求高手指教
题目要求是写一个函数,输入一个数字n,然后函数就输出一个n行n列的数阵,数阵样式举例如下:

n=3
-------------------
1 2 3
8 9 4
7 6 5

n=4
-------------------
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

n=5
-------------------
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

嗯,大致就是这么着,绕着圈子排序


→→→→┐
┌→→┐↓
↑┌→↓↓
↑└←┘↓
└←←←┘

-------------------
有木有高手做出来? 0.0

------解决方案--------------------

PHP code
function Circle($n) {
  $k = $n % 2;
  $ar = array();
  for($i=0; $i= $m) $ar[$y][$x--] = $p++;
    $x++;
    $y--;
    $m++;
    while($y >= $m) $ar[$y--][$x] = $p++;
    $n--;
  }
  if($k) $ar[$y+1][$x+1] = $p;

  $r = '
'; foreach($ar as $v) $r .= ''; return $r.'
' . join(' ', $v) . '
'; } for($i=2;$i'; } ?>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn