輸入一個(gè)矩陣,按照從外向里以順時(shí)針的順序依次打印出每一個(gè)數(shù)字,例如,如果輸入如下矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數(shù)字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
找規(guī)律,找到里面數(shù)據(jù)的位置和遍歷圈數(shù)的關(guān)系,還是很坑爹,線上環(huán)境不如本地環(huán)境優(yōu)越語法錯(cuò)誤沒有及時(shí)看出來,導(dǎo)致提交了很多次。
function printMatrix($matrix)
{
$all = count($matrix[0])*count($matrix);
$result = array();
$cnt = 0;
$start_x=0;
$start_y=0;
$loops = 0;
do{
//右移動(dòng)
while($start_y<count($matrix[0])-$loops&&$cnt<$all){
$result[] = $matrix[$start_x][$start_y];
$cnt++;
$start_y++;
}
$start_y -= 1;
$start_x += 1;
//下移動(dòng)
while($start_x<count($matrix)-$loops&&$cnt<$all){
$result[] = $matrix[$start_x][$start_y];
$start_x++;
$cnt++;
}
$start_x -= 1;
$start_y -= 1;
//左移動(dòng)
while($start_y>=$loops&&$cnt<$all){
$result[] = $matrix[$start_x][$start_y];
$start_y--;
$cnt++;
}
$start_x-= 1;
$start_y+= 1;
$loops+=1; //到最左邊的時(shí)候圈數(shù)量加1
//上移動(dòng)
while($start_x>=$loops&&$cnt<$all){
$result[] = $matrix[$start_x][$start_y];
$start_x--;
$cnt++;
}
$start_x+=1;
$start_y+=1;
}while($cnt<$all);
return $result;
}
$arr = array(array(1,2,3,4),array(5,6,7,8),array(9,10,11,12),array(13,14,15,16));
$result = printMatrix($arr);
echo implode(',',$result);