Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to print a given matrix in spiral form with PHP

1 Answer

0 votes
function PrintMatrixInSpiralForm($matrix) {
    if ($matrix == NULL || count($matrix) == 0) {
            return;
    }
    
    $top = 0;
    $bottom = count($matrix) - 1;
    $left = 0;
    $right = count($matrix[0]) - 1;
    
    while (true) {
        if ($left > $right) {
            break;
        }
        
        // top row
        for ($i = $left; $i <= $right; $i++) {
            echo $matrix[$top][$i] . " ";
        }
        echo "\n";
        $top++; // next row
        
        // next row
        if ($top > $bottom) {
            break;
        }
        
        // right column
        for ($i = $top; $i <= $bottom; $i++) {
            echo $matrix[$i][$right] . " ";
        }
        echo "\n";
        $right--; // previous column
        
        // previous column
        if ($left > $right) {
            break;
        }
        
        // bottom row
        for ($i = $right; $i >= $left; $i--) {
            echo $matrix[$bottom][$i] . " ";
        }
        echo "\n";
        $bottom--; // previous row
        
        // previous row
        if ($top > $bottom) {
            break;
        }
        
        // left column
        for ($i = $bottom; $i >= $top; $i--) {
            echo $matrix[$i][$left] . " ";
        }
        echo "\n";
        $left++; // next column
    }
}
        
$matrix = array(
            array(1, 2, 3, 4), 
            array(5, 6, 7, 8), 
            array(9, 10, 11, 12), 
            array(13, 14, 15, 16)
        );
        
PrintMatrixInSpiralForm($matrix);





/*
run:

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

*/

 



answered Sep 14, 2022 by avibootz
...