2015-10-07 22 views
0

检查相邻小区的代码为棋盘每个棋子B黑色和W为白色 ,其中WB不应共享相同的边缘。错误而在2D阵列

例子:

WBWB 
BWBW 
WBWB 
BWBW 

我的代码是:

#include <iostream> 
using namespace std; 

int main() 
{ 
    int n, m; 
    cin >> n >> m; 
    char chess[4][4]; 
    for (int i = 0;i<n;i++) 
     for (int j = 0;j<m;j++) 
      cin >> chess[i][j]; 

    for (int i = 0;i<n;i++) 
     for (int j = 0;j<m;j++) 
     { 
      if (chess[i][j] == '.') 
      { 
       if (chess[i - 1][j] == 'W' || chess[i + 1][j] == 'W' || chess[i][j + 1] == 'W' || chess[i][j - 1] == 'W') 
        chess[i][j] = 'B'; 
       else 
        chess[i][j] = 'W'; 
      } 
     } 
    for (int i = 0;i<n;i++) 
    { 

     for (int j = 0;j<m;j++) 
      cout << chess[i][j]; 
     cout << endl; 
    } 
    system("pause"); 
    return 0; 
} 

的问题是,当我运行这段代码的输出是:

WBWB 
BWBW 
BBWB 
WBBW 

我调试它,并chess[2][-1]平等到W,它超出了范围,所以它应该是垃圾。

回答

0

您正在使用负数组索引。当ij是零,那么

chess[i - 1][j] 
// and 
chess[i][j - 1] 

变得

chess[-1][j] 
// and 
chess[i][-1] 

,并且使用负数组索引undefined behavior和什么都可能发生。您需要添加边界检查以确保您没有使用小于零或大于3的索引.YOu还需要检查chess[i + 1][j]chess[i][j + 1],因为当ij等于3时,您再次出界。

+0

我明白了未定义的行为。但有没有更容易的方法来进行边界检查? 使用If语句会使代码太长 –