Zig-zag scan an N x N array

前端 未结 8 2187
野的像风
野的像风 2021-01-30 08:32

I have a simple array. The array length always has a square root of an integer. So 16, 25, 36 etc.

$array = array(\'1\', \'2\', \'3\', \'4\' ... \'25\');
         


        
8条回答
  •  不要未来只要你来
    2021-01-30 09:09

    Although there are already many solutions to this question, this is mine:

    The main feature that differentiates it from the other solutions:

    • Only a single loop of complexity O(n)
    • Only primitive (integer) temporary variables

    The source:

    = $bounds) // bottom edge
            {
                $i--;
                $j++;
                $j++;
                $inc = 1;
            }
            if($j >= $bounds) // right edge
            {
                $i++;
                $i++;
                $j--;
                $inc = -1;
            }
            if($j < 0) // left edge
            {
                $j++;
                $inc = 1;
            }
            if($i < 0) // top edge
            {
                $i++;
                $inc = -1;
            }
    
            $output[] = $input[$bounds * $i + $j];
    
            $i = $i - $inc;
            $j = $j + $inc;
            $steps++;
        }
        return $output;
    }
    
    $a = range(1,25);
    var_dump(zigzag($a));
    

    By the way, this sort of algorithm is called "zig zag scan" and is being used heavily for JPEG and MPEG coding.

提交回复
热议问题