Minesweeper (扫雷)
[问题描述]
Have you ever played Minesweeper? It’s a cute little game which comes within a certain Operating
System which name we can’t really remember. Well, the goal of the game is to find where are all the mines within a M × N field. To help you, the game shows a number in a square which tells you how many mines there are adjacent to that square. For instance, supose the following 4 × 4 field with 2 mines (which are represented by an ‘*’ character):
*…
…
.*…
…
If we would represent the same field placing the hint numbers described above, we would end up
with:
*100
2210
1*10
1110
As you may have already noticed, each square may have at most 8 adjacent squares.
[输入]
The input will consist of an arbitrary number of fields. The first line of each field contains two integers
n and m (0 < n, m ≤ 100) which stands for the number of lines and columns of the field respectively.
The next n lines contains exactly m characters and represent the field.
Each safe square is represented by an ‘.’ character (without the quotes) and each mine square
is represented by an ‘*’ character (also without the quotes). The first field line where n = m = 0
represents the end of input and should not be processed.
【题目大意】扫雷游戏,输入一块二维的字符区域,用*表示地雷,然后输出int类型的二维数组,num[i][j]表示与它邻近的八个方位(东,南,西北,东北…)有的地雷数
[样例输入]
4 4
*…
…
.*…
…
3 5
**…
…
.*…
0 0
[样例输出]
Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100
*/
【思路】定义一个移动数组int dx[3]={-1,0,1}; int dy[3]={0,1,-1};
,遍历字符数组,遇到‘*’,则与它邻近的八个点 num[i+dx[a]][j+dy[b]]++
【代码】
#include <iostream>
#include<string.h>
using namespace std;
int dx[3]={-1,0,1};
int dy[3]={0,1,-1};
int n,m;
const int INF=-999;
int main()
{
cin>>n>>m;
char mine[n][m];
int num[n][m];
memset(num, 0, sizeof(num));//扫雷数初始化为0
/***构造字符数组***/
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mine[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(mine[i][j]=='*')
{
for(int a=0;a<3;a++)
{
for(int b=0;b<3;b++)
{
if(((i+dx[a])>=0)&&((i+dx[a])<n)&&((j+dy[b])>=0)&&((i+dy[b])<m)&&(dy[a]!=0||dx[a]!=0))//没有超过边界且不是自身
num[i+dx[a]][j+dy[b]]++;
}
num[i][j]=INF;//自身无穷小,用于标记,等会儿输出“*”
}
}
}
}
for(int i=0;i<n;i++)//按格式输出
{
for(int j=0;j<m;j++)
{
if(num[i][j]<0)
cout<<'*';
else
cout<<num[i][j];
}
cout<<endl;
}
return 0;
}