#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
class Solution {
public:
int dx[4]={0, 1, 0, -1};
int dy[4]={1, 0, -1, 0};
int islandPerimeter(vector<vector<int>>& grid) {
int m=grid.size(), n=grid[0].size();
int ans=0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if (grid[i][j]){
int count=0;
for (int k = 0; k < 4; ++k){
int tx = i + dx[k];
int ty = j + dy[k];
if (tx<0 || tx>=m || ty<0 || ty>=n || !grid[tx][ty]){
++count;
}
}
ans+=count;
}
}
}
return ans;
}
};
int main(){
int m=3,n=3;
vector<vector<int>> board(m, vector<int>(n));
for (int i=0; i<m;i++){
for (int j=0; j<n; j++){
float s= 0+1.0*(rand()%RAND_MAX)/RAND_MAX;
if (s>0.3){
board[i][j]=1;
cout<<board[i][j];
}
else{
board[i][j]=0;
cout<<board[i][j];
}
}
cout<<endl;
}
cout<<"Answer:"<<endl;
Solution S;
int ans=S.islandPerimeter(board);
cout<<ans<<endl;
return 0;
}
010
111
111
Answer:
12
Leetcode463. 岛屿的周长--遍历
最新推荐文章于 2021-08-12 15:03:45 发布