Island Perimeter (中)

来源:互联网 发布:淘宝vip等级在那里看 编辑:程序博客网 时间:2024/06/18 03:08
#include <iostream>#include <vector>using namespace std;int islandPerimeter(vector<vector<int>>& grid) {int t = 0,p=0,u=0;for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){if (grid[i][j] != 0)t = t + 1;if ((i != 3) && (grid[i][j] == grid[i + 1][j]) == 1){p += 1;break;}if ((j != 3) && (grid[i][j] == grid[i][j + 1]) == 1){u += 1;}}}printf("%d\n", t);printf("%d\n", p);printf("%d\n", u);t = 4*t - u - p; printf("%d\n",t); return t;                   };int main()    {vector<vector<int>> test;vector<int> v;int n, temp;cin >> n;test.clear();//输入for (int i = 0; i<n; i++) {v.clear(); //每次记得clear:)for (int j = 0; j < n; j++){cin >> temp;v.push_back(temp);}test.push_back(v);}//输出/*for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){cout << test[i][j] << " ";}cout << endl;}*/islandPerimeter (test);return 0;}


解题思路:

每一个陆地单元格的周长为4,当两单元格上下或者左右相邻时,令周长减2

思路正确的,但是不能设计算法计算相邻单元格个数,

思路不对,不知道怎么办!!

想了四个小时,无意间解决了。



#include <iostream>#include <vector>using namespace std;int islandPerimeter(vector<vector<int>>& grid) {int t = 0,p=0,u=0;for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){if (grid[i][j] != 0){t = t + 1;if ((i != 3) && (grid[i][j] == grid[i + 1][j]) ){p += 1;//break;}if ((j != 3) && (grid[i][j] == grid[i][j + 1])){u += 1;}}}}printf("%d\n", t);printf("%d\n", p);printf("%d\n", u);t = 4*t - 2*(u+ p); printf("%d\n",t); return t;                   };int main()    {vector<vector<int>> test;vector<int> v;int n, temp;cin >> n;test.clear();//输入for (int i = 0; i<n; i++) {v.clear(); //每次记得clear:)for (int j = 0; j < n; j++){cin >> temp;v.push_back(temp);}test.push_back(v);}//输出/*for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){cout << test[i][j] << " ";}cout << endl;}*/islandPerimeter (test);return 0;}

即先判断等于1,在循环判断相邻1的个数。

后来发现不是循环的问题

因为:

if ((i != 3) && (grid[i][j] ==1)&&( grid[i + 1][j] == 1))和语句if ((j != 3) && (grid[i][j] == grid[i][j + 1]) == 1)不等价


代码:

#include <iostream>#include <vector>using namespace std;int islandPerimeter(vector<vector<int>>& grid) {int t = 0, p = 0, u = 0;for (int i = 0; i < 4; i++){for (int j = 0; j < 4; j++){if (grid[i][j] != 0)t = t + 1;if ((i != 3) && (grid[i][j] ==1)&&( grid[i + 1][j] == 1)){p += 1;}if ((j != 3) && (grid[i][j] ==1)&& (grid[i][j + 1] == 1)){u += 1;}}}printf("%d\n", t);printf("%d\n", p);printf("%d\n", u);t = 4 * t - 2*(u + p);printf("%d\n", t);return t;};int main(){vector<vector<int>> test;vector<int> v;int n, temp;cin >> n;test.clear();//输入for (int i = 0; i<n; i++) {v.clear(); //每次记得clear:)for (int j = 0; j < n; j++){cin >> temp;v.push_back(temp);}test.push_back(v);}//输出/*for (int i = 0; i < n; i++){for (int j = 0; j < n; j++){cout << test[i][j] << " ";}cout << endl;}*/islandPerimeter(test);return 0;}

结果: