Minesweeper
时间: 1ms 内存:64M
描述:
Minesweeper Have you ever played Minesweeper? This cute little game comes with a certain operating system whose name we can't remember. The goal of the game is to find where all the mines are located within a M x N field. The game shows a number in a square which tells you how many mines there are adjacent to that square. Each square has at most eight adjacent squares. The 4 x 4 field on the left contains two mines, each represented by a ``*'' character. If we represent the same field by the hint numbers described above, we end up with the field on the right: *... .... .*.. .... *100 2210 1*10 1110
输入:
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 stand for the number of lines and columns of the field, respectively. Each of the next n lines contains exactly m characters, representing the field. Safe squares are denoted by ``.'' and mine squares by ``*,'' both without the quotes. The first field line where n = m = 0 represents the end of input and should not be processed.
输出:
For each field, print the message Field #x: on a line alone, where x stands for the number of the field starting from 1. The next n lines should contain the field with the ``.'' characters replaced by the number of mines adjacent to that square. There must be an empty line between field outputs.
示例输入:
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0
示例输出:
Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100
提示:
参考答案(内存最优[748]):
/* There's a 5-case analytic solution but why bother? */
#include <stdio.h>
main(){
int i,j,k,m,n,s,d;
while (2 == scanf("%d%d",&s,&d)){
int best = -9999999, tot;
for (i=0;i<4096;i++){
for (j=0;j<8;j++){
for (tot=k=0;k<5;k++) tot += ((i>>(j+k))&1)?s:-d;
if (tot >= 0) break;
}
if (j<8) continue;
for (tot=j=0;j<12;j++) tot += ((i>>j)&1)?s:-d;
if (tot > best) best = tot;
}
if (best > 0) printf("%d\n",best);
else printf("Deficit\n");
}
}
参考答案(时间最优[0]):
#include <iostream>
using namespace std;
int main()
{
char a[102][102]={0};
int n,m,count=1;
while(cin>>n>>m){
if(n==0 && m==0)
break;
for(int i=1;i<=n;i++) //input
for(int j=1;j<=m;j++)
cin>>a[i][j];
for(int i=1;i<=n;i++) //计算
for(int j=1;j<=m;j++){
if(a[i][j]=='*')
continue;
a[i][j]='0';
if(a[i-1][j]=='*')
++a[i][j];
if(a[i+1][j]=='*')
++a[i][j];
if(a[i][j+1]=='*')
++a[i][j];
if(a[i][j-1]=='*')
++a[i][j];
if(a[i-1][j-1]=='*')
++a[i][j];
if(a[i-1][j+1]=='*')
++a[i][j];
if(a[i+1][j-1]=='*')
++a[i][j];
if(a[i+1][j+1]=='*')
++a[i][j];
}
if(count!=1)
cout<<endl;
cout<<"Field #"<<count++<<':'<<endl;
for(int i=1;i<=n;i++){ //输出
for(int j=1;j<=m;j++){
cout<<a[i][j];
}
cout<<endl;
}
}
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。