B. Little Pigs and Wolves

B. Little Pigs and Wolves
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.

A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.

They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.

What is the maximum number of little pigs that may be eaten by the wolves?

Input

The first line contains integers n and m (1 ≤ n, m ≤ 10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow n lines containing m characters each — that is the grid description. "." means that this cell is empty. "P" means that this cell contains a little pig. "W" means that this cell contains a wolf.

It is guaranteed that there will be at most one wolf adjacent to any little pig.

Output

Print a single number — the maximal number of little pigs that may be eaten by the wolves.

Sample test(s)
input
2 3
PPW
W.P
output
2
input
3 3
P.W
.P.
W.P
output
0
Note

In the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.


解题说明:此题需要注意边界问题,为了简单,只需要从1开始存储即可,这样就能保证数组不会越界。然后判断每个W位置周围是否存在P即可,由于题目中已经说明一只P周围最多只有一只W,所以不需要判断某只P可能被两只W吃而导致的错误。


#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
	int n,m,i,j,count;
	char a[12][12];
	scanf("%d %d",&n,&m);
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=m;j++)
		{
			cin>>a[i][j];
		}
	}
	count=0;
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=m;j++)
		{
			if(a[i][j]=='W'&&(a[i-1][j]=='P'||a[i+1][j]=='P'||a[i][j-1]=='P'||a[i][j+1]=='P'))
			{
				count++;
			}
		}
	}
	printf("%d\n",count);


	return 0;
}


你可能感兴趣的:(B. Little Pigs and Wolves)