扫雷游戏
#include<stdio.h>
#include<iostream>
using namespace std;
bool map[105][105];
int sum[105][105];
int main() {
int n, m;
cin >> n >> m;
char ch;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ch;
if (ch == '*') map[i][j] = true;
else map[i][j] = false;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == false) {
if (map[i-1][j] == true && i-1 >= 0) sum[i][j]++;
if (map[i+1][j] == true && i+1 <= n) sum[i][j]++;
if (map[i][j+1] == true && j+1 <= m) sum[i][j]++;
if (map[i][j-1] == true && j-1 >= 0) sum[i][j]++;
if (map[i-1][j-1] == true && (i-1 >= 0 && j-1 >= 0)) sum[i][j]++;
if (map[i+1][j+1] == true && (i+1 <= n && j+1 <= m)) sum[i][j]++;
if (map[i+1][j-1] == true && (i+1 <= n && j-1 >= 0)) sum[i][j]++;
if (map[i-1][j+1] == true && (i-1 >= 0 && j+1 <= m)) sum[i][j]++;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == true) cout << '*';
else cout << sum[i][j];
}
if (i < n)
cout << endl;
}
#include<iostream>
using namespace std;
bool map[105][105];
int sum[105][105];
int main() {
int n, m;
cin >> n >> m;
char ch;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ch;
if (ch == '*') map[i][j] = true;
else map[i][j] = false;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == false) {
if (map[i-1][j] == true && i-1 >= 0) sum[i][j]++;
if (map[i+1][j] == true && i+1 <= n) sum[i][j]++;
if (map[i][j+1] == true && j+1 <= m) sum[i][j]++;
if (map[i][j-1] == true && j-1 >= 0) sum[i][j]++;
if (map[i-1][j-1] == true && (i-1 >= 0 && j-1 >= 0)) sum[i][j]++;
if (map[i+1][j+1] == true && (i+1 <= n && j+1 <= m)) sum[i][j]++;
if (map[i+1][j-1] == true && (i+1 <= n && j-1 >= 0)) sum[i][j]++;
if (map[i-1][j+1] == true && (i-1 >= 0 && j+1 <= m)) sum[i][j]++;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == true) cout << '*';
else cout << sum[i][j];
}
if (i < n)
cout << endl;
}
}
用了比较笨的方法AC,不知道有没有更好更简洁的办法可以分享