蓝桥每周练二 扫雷问题(坐标的移动)

本文详细解析了扫雷游戏的算法实现,通过定义移动数组和遍历字符数组的方法,计算每个安全方格周围八方位的地雷数量,最终输出二维数组表示的地雷分布情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值