查找矩阵中的相邻位置
我很无聊,所以我创建了一个小型控制台扫雷游戏,在编写它时,我必须找到 size*size 矩阵中元素的相邻位置,该矩阵表示为元素向量和一个保存大小值的变量。我不想返回相邻元素的实际值,而是返回它们的位置,以便我可以将其用作公共函数(否则客户端可以看到地雷所在的位置:P)。
例如,对于字段 eq 0 和大小 eq 3,函数应返回 {1, 3, 4}:
1 0 0 0 1 0
0 0 0 => 1 1 0
0 0 0 0 0 0
嗯,基本上看起来像这样:
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 +上校)。
这是一个快速的解决方案,但它并不优雅,我敢打赌有更好的方法来做到这一点。有什么想法吗?
I'v been bored so I created a small console minesweeper game and while writting it I had to find the neighbor positions of an element in a size*size matrix which is represented as an vector of elements and one variable which holds the size value. I didn't want to return the actual values of the neighbor elements but their positions so that I could use that as a public function (otherwise the client could see where the mines are at :P).
For example for field eq 0 and size eq 3 the function should return {1, 3, 4}:
1 0 0 0 1 0
0 0 0 => 1 1 0
0 0 0 0 0 0
Well, basicaly it looks like this:
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) is just converting coordinates into field number (row*size + col).
This is a fast solution but it's not elegant and I bet there's some better way to do this. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你的代码太糟糕了。这是一个更好的尝试(已修复,抱歉):
Yeah, your code is awful. Here's a better attempt (fixed, sorry):
为什么不使用对象作为坐标?我认为这会更具可读性:
Why don't using an object for your coordinates ? I think this will be more readable:
这是 Pavel 解决方案的固定代码:
Here's the fixed code for Pavel's solution: