Created
May 29, 2019 06:34
-
-
Save zhusaidong/741bcb46fb49c8f023925af5f68d690a to your computer and use it in GitHub Desktop.
有一张地图,如下图,"-" 代表海洋、"+" 代表陆地,用你最擅长的方式,取出陆地的坐标
This file contains 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 | |
/** | |
假如有一张地图,如下图,"-" 代表海洋、"+" 代表陆地,用你最擅长的方式,取出陆地的坐标。 | |
--++----++--+++--- | |
-++++----+++++++-- | |
-+++----++++------ | |
-----++------++++- | |
---++++++-----+++- | |
-----+++------+++- | |
* @author zhusaidong [zhusaidong@gmail.com] | |
*/ | |
/** | |
* 数字化地图 | |
* | |
* @param string $map | |
* @param bool $debug | |
* | |
* @return array | |
*/ | |
function digitalMaps(string $map, bool $debug = FALSE) : array | |
{ | |
$maps = explode(PHP_EOL, $map); | |
$digitalMaps = []; | |
foreach($maps as $map) | |
{ | |
$digitalMaps[] = array_map(function($v) | |
{ | |
return $v == '-' ? 0 : 1; | |
}, str_split($map)); | |
} | |
//echo digital map | |
if($debug) | |
{ | |
echo implode(PHP_EOL, array_map(function($v) | |
{ | |
return implode('', $v); | |
}, $digitalMaps)) . PHP_EOL; | |
} | |
return $digitalMaps; | |
} | |
/** | |
* 查找大陆 | |
* | |
* @param array $digitalMaps | |
* | |
* @return array | |
*/ | |
function findLands(array $digitalMapsOrigin) : array | |
{ | |
$digitalMaps = $digitalMapsOrigin; | |
$lands = []; | |
for($x = 0; $x < count($digitalMaps); $x++) | |
{ | |
for($y = 0; $y < count($digitalMaps[$x]); $y++) | |
{ | |
if($digitalMaps[$x][$y] == 1 and !empty($land = findLandBlock($digitalMaps, $x, $y))) | |
{ | |
$lands[] = $land; | |
} | |
} | |
} | |
return $lands; | |
} | |
/** | |
* 搜索大陆块 | |
* | |
* @param array $digitalMaps | |
* @param int $x | |
* @param int $y | |
* | |
* @return array | |
*/ | |
function findLandBlock(array &$digitalMaps, int $x, int $y) : array | |
{ | |
$landBlock = []; | |
for($i = -1; $i <= 1; $i++) | |
{ | |
for($j = -1; $j <= 1; $j++) | |
{ | |
if(abs($i) + abs($j) == 2) | |
{ | |
continue; | |
} | |
if(isset($digitalMaps[$x + $i][$y + $j]) and $digitalMaps[$x + $i][$y + $j] == 1) | |
{ | |
$digitalMaps[$x + $i][$y + $j] = 2; | |
$landBlock[] = [$x + $i, $y + $j]; | |
$landBlock = array_merge($landBlock, findLandBlock($digitalMaps, $x + $i, $y + $j)); | |
} | |
} | |
} | |
return $landBlock; | |
} | |
$map = <<<eof | |
--++----++--+++--- | |
-++++----+++++++-- | |
-+++----++++------ | |
-----++------++++- | |
---++++++-----+++- | |
-----+++------+++- | |
eof; | |
$lands = findLands(digitalMaps($map, FALSE)); | |
//输出 | |
echo implode(PHP_EOL, array_map(function($v) | |
{ | |
return implode(' ', array_map(function($v) | |
{ | |
return '(' . implode(',', $v) . ')'; | |
}, $v)); | |
}, $lands)) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment