섬 문제 간단한 해법

문제 풀이 사고방식: 차례로 만나는 모든 1을 0으로 설정한다.



$strIsland = <<<STR
1 1 1 1 0
1 1 0 1 0
1 1 0 0 1
0 0 0 1 0
STR;

$graph = [];

$lines = explode(PHP_EOL, $strIsland);

$row = 0;
foreach( $lines as $line )
{
    $items = explode( ' ', $line );

    $graph[$row] = [];
    foreach( $items as $item )
    {
        $graph[$row][] = $item;
    }

    $row++;
}

print_graph($graph);


$color = 0;
foreach( $graph as $row_index => $rows )
{
    foreach( $rows as $column_index => $item )
    {
        if( isset($graph[$row_index][$column_index]) && 1 == $graph[$row_index][$column_index] )
        {
            $color++;
        }

        erase2Zero($graph, $row_index, $column_index );
    }
}


function erase2Zero(&$graph, $row_index, $column_index)
{
    if( !isset( $graph[$row_index][$column_index] ) )
    {
        return;
    }

    if( $graph[$row_index][$column_index] == 0 )
    {
        return;
    }

    if( $graph[$row_index][$column_index] == 1 )
    {
        $graph[$row_index][$column_index] = 0;
    }

    erase2Zero( $graph, $row_index, $column_index - 1 );
    erase2Zero( $graph, $row_index, $column_index + 1 );
    erase2Zero( $graph, $row_index - 1, $column_index );
    erase2Zero( $graph, $row_index + 1, $column_index );
}


echo PHP_EOL;
echo PHP_EOL;

print_graph($graph);

echo 'island count: ', $color, PHP_EOL;




function print_graph($arr)
{
    foreach( $arr as $line )
    {
        foreach( $line as $item )
        {
            echo $item, ' ';
        }

        echo PHP_EOL;
    }
}



좋은 웹페이지 즐겨찾기