2011-05-31 99 views
-1

这里的链接的问题:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=13&page=show_problem&problem=1130UVA 10189:扫雷

这是我的代码,它完美的作品;然而,只要我提交它就会给出错误的答案。有人知道为什么吗?

注:我用2个额外的行和列填充矩阵,以便当我检查第一列的左边或最后一行的底部时,我不会收到错误。

//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; 
} 
+1

@Neil流缓冲区,它使代码,如果你有更复杂检查循环中的边界条件。我认为在它周围添加1行边框是一个完美的解决方案。 – 2011-05-31 16:35:49

+0

@Jeff我不确定它的确如此 - 它肯定会让有经验的C++程序员难以阅读 - 所有这些+1。只是看了一眼,我认为他有一个错误 - 因此我原来的评论。 – 2011-05-31 16:42:45

回答

2

没有试图在运行之间清除arr[][](或在启动时清除),因此在第4个位置带有*的4x4雷区将导致下一个3x3雷区具有不正确的值。

2
if(arr[i-1][j-1] == '*' || arr[i-1][j] == '*' || arr[i-1][j+1] == '*') 
    count++; 

除非我的误解,并不只算1个矿时,有可能是3?

+0

对不起,我想在这里粘贴之前缩短代码,所以我做了这个诀窍。但是,我提交了8如果是,它不起作用。 – 2011-05-31 16:36:18

+0

好吧,现在我修复了if语句,我仍然得到了错误的答案! – 2011-05-31 16:45:15

2

您应该清除所有'。'的arr。处理每个“字段”前的字符。否则,您的边界检查将包含错误的数据。

for (int x=0; x < 102; ++x) 
    for (int y=0; y < 102; ++y) 
    arr[x][y] = '.'; 
0

while循环结束

for (int i = 1; i < n + 1; i++) { //Rows 
    for (int j = 1; j < m + 1; j++) { //Columns 
     arr[i][j] = '.'; 
    } 
} 

必须正确之前重新注入点的数组,你可以替换使用arr[i][j] = count + 48;