leetcode-463. 岛屿的周长

题目

463. 岛屿的周长

解法

依题遍历陆地的四个边,如果靠近水,那么算到周长里面,否则不算

<?php
class Solution {
/**
* @param Integer[][] $grid
* @return Integer
*/
function islandPerimeter($grid) {
if (empty($grid)) {
return 0;
}
$per = 0;
foreach ($grid as $rowKey => $rowGrid) {
foreach ($rowGrid as $colKey => $colItem) {
if ($colItem != 1) {
continue;
}
$per += intval(!isset($grid[$rowKey - 1][$colKey]) || $grid[$rowKey - 1][$colKey] == 0);
$per += intval(!isset($grid[$rowKey][$colKey + 1]) || $grid[$rowKey][$colKey + 1] == 0);
$per += intval(!isset($grid[$rowKey + 1][$colKey]) || $grid[$rowKey + 1][$colKey] == 0);
$per += intval(!isset($grid[$rowKey][$colKey - 1]) || $grid[$rowKey][$colKey - 1] == 0);
}
}
return $per;
}
}

还有一种深度遍历的方式

class Solution {
/**
* @param Integer[][] $grid
* @return Integer
*/
function islandPerimeter($grid) {
if (empty($grid)) {
return 0;
}
$per = 0;
foreach ($grid as $rowKey => $rowGrid) {
foreach ($rowGrid as $colKey => $colItem) {
if ($grid[$rowKey][$colKey] == 1) {
$per += $this->dfs($grid, $rowKey, $colKey);
}
}
}
return $per;
}
public function dfs(&$grid, $rowKey, $colKey) {
if (!isset($grid[$rowKey][$colKey])) {
return 0;
}
if ($grid[$rowKey][$colKey] == 0) {
return 0;
}
if ($grid[$rowKey][$colKey] == 2) {
return 0;
}
$grid[$rowKey][$colKey] = 2;
$per = 0;
$per += intval(!isset($grid[$rowKey - 1][$colKey]) || $grid[$rowKey - 1][$colKey] == 0);
$per += intval(!isset($grid[$rowKey][$colKey + 1]) || $grid[$rowKey][$colKey + 1] == 0);
$per += intval(!isset($grid[$rowKey + 1][$colKey]) || $grid[$rowKey + 1][$colKey] == 0);
$per += intval(!isset($grid[$rowKey][$colKey - 1]) || $grid[$rowKey][$colKey - 1] == 0);
$per += $this->dfs($grid, $rowKey - 1, $colKey);
$per += $this->dfs($grid, $rowKey, $colKey + 1);
$per += $this->dfs($grid, $rowKey + 1, $colKey);
$per += $this->dfs($grid, $rowKey, $colKey - 1);
return $per;
}
}
posted @   吴丹阳-V  阅读(42)  评论(0编辑  收藏  举报
编辑推荐:
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 如何给本地部署的DeepSeek投喂数据,让他更懂你
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· 从 Windows Forms 到微服务的经验教训
点击右上角即可分享
微信分享提示