Here's the link to the problem: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1130
This is my code and it works perfectly; however, it gives wrong answer whenever I submit it. Does anybody know why?
NOTE: I pad the matrix with 2 extra rows and columns so that when I'm checking the left of the first column or the bottom of the last row, I don't get an error.
//A minesweeper generator
#include <iostream>
#include <sstream>
using namespace std;
char arr[102][102]; //2D dynamic array used temporarily
int main() {
int n, m; //Rows and columns
int count = 0, recordNum = 0; //Number of mines around the current dot
while(true) { //Keep processing records until "0 0" is encountered
cin >> n >> m;
if(n == 0 && m == 0 ) //End of input
break;
//Read the values into the array
for(int i = 1; i < n+1; i++) { //Rows
for(int j = 1; j < m+1; j++) { //Columns
cin >> arr[i][j];
}
}
//Process the values of the array and generate the numbers
for(int i = 1; i < n+1; i++) { //Rows
for(int j = 1; j < m+1; j++) { //Columns
if(arr[i][j] == '*')
continue;
else { //Count the number of mines around this dot
if(arr[i-1][j-1] == '*')
count++;
if(arr[i-1][j] == '*')
count++;
if(arr[i-1][j+1] == '*')
count++;
if(arr[i][j-1] == '*')
count++;
if(arr[i][j+1] == '*')
count++;
if(arr[i+1][j-1] == '*')
count++;
if(arr[i+1][j] == '*')
count++;
if(arr[i+1][j+1] == '*')
count++;
}
//Create a buffer to convert the count to a char
stringstream buffer;
buffer << count;
arr[i][j] = buffer.str().at(0);
count = 0; //Finally reset the counter
}
}
if(recordNum > 0)
cout << endl;
recordNum++;
cout << "Field #" << recordNum << ":\n";
//Output the values
for(int i = 1; i < n+1; i++) { //Rows
for(int j = 1; j < m+1; j++) { //Columns
cout << arr[i][j];
}
cout << endl;
}
}
return 0;
}
No attempt is made to clear out arr[][]
between runs (or clear at start), so a 4x4 minefield with a * in the 4th position will cause a next 3x3 minefield to have incorrect values.