Source: http://oucee.openjudge.cn/17b1/4/ 4: Island perimeter
Total time limit: 1000ms memory limit: 65536kB
Description
A n*m two-dimensional array is used to represent the map, 1 for land, 0 for seawater, and each for a 1*1 area. The grids in the map can only be connected horizontally or vertically (not diagonally), and the connected land is called an island, and the entire map is surrounded by seawater. Suppose there will only be one island in the given map, and there will be no lake in the island (i.e. there will be no water surrounded by land). Please determine the perimeter of the island in the given two-dimensional map.
input
The first behavior, N and M, indicates the size of the map (1<=n<=100, 1<=m<=100). Next n rows, each row has a number of m, each describing the value of each lattice. The values are separated by a space.
Output
There is only one row, that is, the perimeter of the island (positive integer).
Sample Input
3 4
1 1 1 0
0 1 0 0
1 1 0 0
Sample Output
14
-----------------------------------------------------
Thinking of solving problems
Count the number of changes from 0 to 1 by row and column and multiply by 2
-----------------------------------------------------
Code
#include <iostream> #include <string.h> using namespace std;
int main () {int n, m, I, J;
CIN >> n >> m;
int cnt = 0;
int **mat = new Int*[n];
for (i=0; i<n; i++) {Mat[i] = new Int[m];
} for (i=0, i<n; i++) {for (j=0; j<m; J + +) {cin >> mat[i][j];
}} if (n==1) {cnt = 2;
for (i=0; i<m; i++) {if (mat[0][i] = = 1) {cnt + = 2;
}} return CNT;
} if (m==1) {cnt = 2;
for (i=0; i<n; i++) {if (mat[i][0] = = 1) {cnt + = 2;
}} return CNT;
} for (i=0; i<n; i++) {if (mat[i][0] = = 1) {cnt + = 2;
} for (j=1; j<m; J + +) {if (mat[i][j] = = 1 && mat[i][j-1] = = 0) {cnt + = 2;
}}} for (j=0; j<m; J + +) {if (mat[0][j] = = 1) {cnt + = 2;
} for (I=1; i<n; i++) {if (mat[i][j] = = 1 && mat[i-1][j] = = 0) {cnt + = 2;
}}} cout << cnt;
for (i=0; i<n; i++) {delete[] mat[i]; } delete[] Mat
return 0; }