问题描述:
计算一片水域中一个岛的周长
思路: 根据陆地的位置计算四周(四个方向)水域的数量,即该部分边长,注意矩阵边界的四周需要特别考量
代码如下:
class Solution {
public int islandPerimeter(int[][] grid) {
int lowerBound=grid.length-1; //index of the lowerBound of matrix
int rightBound=grid[0].length-1; //index of the rightBound of matrix
int counter=0;
for(int i=0; i<=lowerBound; i++){
for(int j=0; j<=rightBound; j++){
if(grid[i][j]==1){ //if this is a land
boolean up;
boolean down;
boolean left;
boolean right;
if(i==0){
up=false; //if at line 0, then up=false(is a water grid)
}
else{
if(grid[i-1][j]==0){
up=false;
}
else{
up=true;
}
}
if(i==lowerBound){
down=false; //if at last one, then down=false(is a water grid)
}
else{
if(grid[i+1][j]==0){
down=false;
}
else{
down=true;
}
}
if(j==0){
left=false; //if at column 0, then left=false(is a water grid)
}
else{
if(grid[i][j-1]==0){
left=false;
}
else{
left=true;
}
}
if(j==rightBound){
right=false; //if at column last, then right=false(is a water grid)
}
else{
if(grid[i][j+1]==0){
right=false;
}
else{
right=true;
}
}
counter=counter+whichCase(up, down, left, right);
}
}
}
return counter;
}
private int whichCase(boolean up, boolean down, boolean left, boolean right){
//true: is a land //false: is a water
int trueCounter=0;
int falseCounter=0;
if (up==true){
trueCounter++;
}
else{
falseCounter++;
}
if (down==true){
trueCounter++;
}
else {
falseCounter++;
}
if (left==true){
trueCounter++;
}
else{
falseCounter++;
}
if (right==true){
trueCounter++;
}
else{
falseCounter++;
}
return falseCounter;
}
}
时间复杂度: O(mn)