首页 > 代码库 > uva10189

uva10189

解题思路见代码注释
技术分享
/////////////////////////////////
//UVA 100 - Minesweeper 
//                               
//DATA 2016/10/27      
//
//TIME 0ms                   
/////////////////////////////////
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

const int N = 110;

char map[N][N];
int ans[N][N];
int n, m;

int get_ans(int x, int y)
{
    int cnt = 0;
    //依次检查8个区域的是否有地雷
    if (map[x - 1][y - 1] == *) cnt++;
    if (map[x - 1][y] == *) cnt++;
    if (map[x - 1][y + 1] == *) cnt++;
    if (map[x][y - 1] == *) cnt++;
    if (map[x][y + 1] == *) cnt++;
    if (map[x + 1][y - 1] == *) cnt++;
    if (map[x + 1][y] == *) cnt++;
    if (map[x + 1][y + 1] == *) cnt++;
    return cnt;
}

int main()
{
    cin >> n >> m;
    int tests = 0;
    while (!(n == 0 && m == 0)) {
        tests++;
        memset(map, 0, sizeof(map));
        //第零行和第零列都空出来,这样方便统计地雷数
        for (int i = 1; i <= n; i++)
            cin >> map[i] + 1;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (map[i][j] != *)
                    //如果该区域没地雷,统计他周边的地雷数
                    ans[i][j] = get_ans(i, j);
                else
                    //-1为有地雷的标志
                    ans[i][j] = -1;
            }
        }
        printf("Field #%d:\n", tests);
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (ans[i][j] == -1) cout << *;
                else cout << ans[i][j];
            }
            cout << endl;
        }
        cin >> n >> m;
        //注意:当n = 0且m = 0的时候不能再换行
        if (!(n == 0 && m == 0)) cout << endl;
    }
    return 0;
}
View Code

 

uva10189