Programming Challenges 习题 1.6.2

PC/UVa:110102/10189

Minesweepers

题目要求计算n * m矩阵中每个非地雷位置周围的地雷数目和,没有什么难度,但是最主要的问题是输出格式,每两个输出结果之间用一个空行隔开,最后一个输出结果后没有空行。

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
	char field[100][100];
	int row = 0, col = 0;
	int num = 1;
	while (cin >> row >> col){
		if (row == 0 && col == 0) break;
		if (num >= 2) cout << endl;
		memset(field, 0, 100 * 100 * sizeof(char));
		for (int i = 0; i < row; i++)
		{
			for (int j = 0; j < col; j++)
			{
				cin >> field[i][j];
			}
		}
		cout << "Field #" << num++ << ":" << endl;
		for (int i = 0; i < row; i++)
		{
			for (int j = 0; j < col; j++)
			{
				if (field[i][j] == '.'){
					int cnt = 0;
					if (i - 1 >= 0 && j - 1 >= 0) 
						cnt += field[i - 1][j - 1] == '*' ? 1 : 0;
					if (i - 1 >= 0)
						cnt += field[i - 1][j] == '*' ? 1 : 0;
					if (i - 1 >= 0 && j + 1 < col)
						cnt += field[i - 1][j + 1] == '*' ? 1 : 0;
					if (j + 1 < col)
						cnt += field[i][j + 1] == '*' ? 1 : 0;
					if (i + 1 < row && j + 1 < col)
						cnt += field[i + 1][j + 1] == '*' ? 1 : 0;
					if (i + 1 < row)
						cnt += field[i + 1][j] == '*' ? 1 : 0;
					if (i + 1 < row && j - 1 >= 0)
						cnt += field[i + 1][j - 1] == '*' ? 1 : 0;
					if (j - 1 >= 0)
						cnt += field[i][j - 1] == '*' ? 1 : 0;
					cout << cnt;
				}
				else cout << '*';
			}
			cout << endl;
		}
		//cout << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值