2009-11-05 162 views
2

我很无聊,所以我创建了一个小型控制台扫雷游戏,并且在写它的同时,我不得不在元素的大小*尺寸矩阵中找到元素的邻居位置,一个保存大小值的变量。我不想返回邻居元素的实际值,但他们的位置,以便我可以使用它作为一个公共职能(否则客户端可以看到地雷在哪里:P)。查找矩阵中的邻居位置

例如用于现场当量0和大小当量3函数应该返回{1,3,4}:

1 0 0 0 1 0 
0 0 0 => 1 1 0 
0 0 0 0 0 0 

那么,basicaly它看起来像这样:

vector<int> adjecantPositions(int field, int size) 
{ 
    int row = field/size; 
    int col = field % size; 
    vector<int> result; 

    /* 
     1 0 0 
     1 0 0 
     1 0 0 
    */  
    if (col > 0) 
    { 
     result.push_back(calcField(row, col-1, size)); 

     if (row > 0)  
      result.push_back(calcField(row-1, col-1, size)); 
     if (row < size - 1) 
      result.push_back(calcField(row+1, col-1, size)); 
    } 

    /* 
     0 0 1 
     0 0 1 
     0 0 1 
    */ 
    if (col < size - 1) 
    { 
     result.push_back(calcField(row, col+1, size)); 

     if (row > 0)  
      result.push_back(calcField(row-1, col+1, size)); 
     if (row < size - 1) 
      result.push_back(calcField(row+1, col+1, size)); 

    } 

    /* 
     0 1 0 
     0 0 0 
     0 1 0 
    */ 
    if (row > 0) 
     result.push_back(calcField(row-1, col, size)); 
    if (row < size - 1) 
     result.push_back(calcField(row+1, col, size)); 

    return result; 
} 

calcField( int,int,int)只是将坐标转换为字段编号(row * size + col)。

这是一个快速的解决方案,但它不是优雅的,我敢打赌,有一些更好的方法来做到这一点。有任何想法吗?

回答

1

是的,你的代码很糟糕。这里有一个更好的尝试(固定,不好意思):

for (int dx=-1; dx<=1; dx++) 
    for (int dy=-1; dy<=1; dy++) 
    if (dx || dy){ 
     int x = row+dx, y=col+dy; 
     if (x >= 0 && x < size && y >= 0 && y < size) 
     result.push_back(calcField(x, y, size)); 
    } 
+0

此代码返回不正确的结果,但我看到你穿越前后场形成3x3矩阵......我不明白,我没有想到这一点。 – schmrz 2009-11-05 11:56:25

0

这里的固定代码帕维尔的解决方案:

for (int drow = -1; drow <= 1; drow++) 
{ 
    int rrow = row + drow; 

    for (int dcol = -1; dcol <= 1; dcol++) 
    { 
     int rcol = col + dcol; 

     if (rrow >= 0 && rrow < size && rcol >= 0 && rcol < size 
      && !(rrow == row && rcol == col)) 
      result.push_back(calcField(rrow, rcol, size)); 
    } 
} 
1

为什么不使用你的坐标的对象?我认为这将是更具可读性:

struct Coords 
{ 
    int row; 
    int col; 

    Case(row, col) : row(row), col(col) {} 
    bool isValid(int size) 
    { 
    return row >= 0 && col >= 0 && row < size && col < size; 
    } 
} 

vector<Coords> adjecantPositions(const Coords & field, int size) 
{ 
    vector<Coords> result; 
    for(int drow = -1; drow <= 1; ++drow) 
    { 
    for(int dcol = -1; dcol <= 1; ++dcol) 
    { 
     Coords current(field.row + drow, field.col + dcol); 
     if(current.isValid(size)) 
     { 
     result.push_back(current); 
     } 
    } 
    } 
    return result; 
}