Last active
October 13, 2017 06:18
-
-
Save FatBoyXPC/acf69a23474cf597fd90e8cdc47a9a63 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$lines = getLines(); | |
$ones = getOnes($lines); | |
$groups = buildGroups($ones); | |
$groupCounts = array_map(function ($group) { | |
return count($group); | |
}, $groups); | |
sort($groupCounts); | |
echo end($groupCounts), PHP_EOL; | |
function getLines() | |
{ | |
$lines = []; | |
while($f = fgets(STDIN)){ | |
$lines[] = explode(' ', $f); | |
} | |
return array_slice($lines, 2); | |
} | |
function getOnes($matrix) | |
{ | |
$ones = []; | |
foreach ($matrix as $rowIndex => $row) { | |
foreach ($row as $columnIndex => $column) { | |
$cell = (int) trim($column); | |
if ($cell === 1) { | |
$index = oneKey($rowIndex, $columnIndex); | |
$ones[$index] = [$rowIndex, $columnIndex]; | |
} | |
} | |
} | |
return $ones; | |
} | |
function oneKey($row, $column) | |
{ | |
return "{$row}-{$column}"; | |
} | |
function buildGroups($ones) | |
{ | |
$groups = []; | |
foreach ($ones as $key => $coords) { | |
$groups[] = findNeighbors($ones, $coords, [$key => $coords]); | |
} | |
return $groups; | |
} | |
function findNeighbors($ones, $coords, $foundNeighbors) | |
{ | |
$neighbors = neighbors($coords); | |
foreach ($neighbors as $neighborKey => $neighborArr) { | |
if (isset($ones[$neighborKey])) { | |
unset($ones[$neighborKey]); | |
$foundNeighbors[$neighborKey] = $neighborArr; | |
$foundNeighbors = findNeighbors($ones, $neighborArr, $foundNeighbors); | |
} | |
} | |
return $foundNeighbors; | |
} | |
function neighbors($position) | |
{ | |
list($x, $y) = $position; | |
$northY = $y - 1; | |
$southY = $y + 1; | |
$eastX = $x + 1; | |
$westX = $x - 1; | |
$northeast = [$eastX, $northY]; | |
$southeast = [$eastX, $southY]; | |
$southwest = [$westX, $southY]; | |
$northwest = [$westX, $northY]; | |
$north = [$x, $northY]; | |
$east = [$eastX, $y]; | |
$south = [$x, $southY]; | |
$west = [$westX, $y]; | |
return [ | |
oneKey(...$northeast) => $northeast, | |
oneKey(...$east) => $east, | |
oneKey(...$southeast) => $southeast, | |
oneKey(...$south) => $south, | |
oneKey(...$southwest) => $southwest, | |
oneKey(...$west) => $west, | |
oneKey(...$northwest) => $northwest, | |
oneKey(...$north) => $north, | |
]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment