Store the rectangular area in a character array. Consider the element . If it differs from s[i + 1][j], then there is a border of length between them (that is, there is a border below ).
Similarly, if differs from s[i][j + 1], then there is also a border of length between them (that is, there is a border to the right of ).
It remains to iterate over all positions and, for each of them, count the number of bottom and right borders.
Example
The border between the states is shown in red. Its length is .
Algorithm implementation
The territories of the states are stored in the array .
#define MAX 110
char s[MAX][MAX];Read the input data.
scanf("%d %d\n", &w, &h);
for (i = 0; i < h; i++)
gets(s[i]);Compute the total length of the vertical borders.
for (i = 0; i < h; i++)
for (j = 0; j < w - 1; j++)
if (s[i][j] != s[i][j + 1]) res++;Compute the total length of the horizontal borders.
for (i = 0; i < h - 1; i++)
for (j = 0; j < w; j++)
if (s[i][j] != s[i + 1][j]) res++;Print the answer.
printf("%d\n", res);Algorithm implementation – string
The territories of the states are stored in the array .
vector<string> s;Read the input data.
cin >> w >> h;
s.resize(h);
for (i = 0; i < h; i++)
cin >> s[i];Compute the total length of the vertical borders.
for(i = 0; i < h; i++)
for(j = 0; j < w - 1; j++)
if (s[i][j] != s[i][j+1]) res++;Compute the total length of the horizontal borders.
for(i = 0; i < h - 1; i++)
for(j = 0; j < w; j++)
if (s[i][j] != s[i+1][j]) res++;Print the answer.
cout << res << endl;