如何检查二维数组上的周围数字?

How to check the surrounding numbers on a two dimensional array?

本文关键字:周围 数字 二维数组 何检查 检查      更新时间:2023-10-16

嘿,所以我想创建一个扫雷的文本版本。我创建了一个输出 1 和 0 的网格(地雷用 0 表示,任何不是地雷的东西都是 1(。我将如何检查每个非地雷周围有多少个地雷(或每个数字 1 周围有多少个 0(。然后更新数字以显示与它们相邻的地雷数量。

如果有人至少能告诉我从哪里开始,我将不胜感激:)

#include "pch.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <string>
using namespace std;

int main()
{
string mystring;
int grid[5][5] = {
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1}
};
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
int rNum = (rand() % 10) + 1;
if (rNum == 1 || rNum == 2)
{
grid[i][j] = 0; // mines are 0
}
else grid[i][j] = 1; // non-mines are represented by 1
std::cout << setw(4) << grid[i][j] << setw(4);
}
std::cout << std::endl;
}

}

我在Java中做了一件非常相似的事情;尽管我没有用0来表示炸弹,而是使用了9s,因为非地雷有可能被0地雷包围,所以不可能被9个或更高的地雷包围。 这是我的方法:

for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
if(grid[x][y] != 9) {
byte count = 0;
for(int lx = -1; lx <= 1; lx++) {  //think of lx and ly as temporary x y
if((x+lx) >= 0 && (x+lx) < 5) {
for(int ly = -1; ly <= 1; ly++) {
if((y+ly) >= 0 && (y+ly) <5) {
if(grid[x+lx][y+ly] == 9) {
count += 1;
}
}
}
}
}
grid[x][y] = count;
}
}
}

基本上,它的作用是滚动网格上的每个点,检查它是否是炸弹。 如果不是,它会检查接触它的 8 个方块中的每一个(只要它们在网格的边界内,就不希望出现未定义的索引错误(。 然后,如果它们是炸弹,它会在计数中增加一个。 最后,它将瓷砖上的数字设置为等于触摸炸弹的数量。

就我而言,我将指针传递给类型 wchar_t 的 2d 数组,但可以根据需要是任何类型。假设你有 2d 数组,你可以用 [X,Y] 引用每个单元格,但你还需要检查该单元格是否具有所有邻居(例如,表格的左上角单元格只有 3 个邻居(:

void getNeighbours(wchar_t* scr,int x, int y)
{
// Left
if((x-1)>=0)
{
// value = scr[getIndex(x-1,y)];
}
// Right
if((x+1)<tableWidth)
{
// value = scr[getIndex(x+1,y)];
}
//Up
if((y-1)>=0)
{
// value = scr[getIndex(x,y-1)];
}
//Down
if((y+1)<tableHeight)
{
// value = scr[getIndex(x,y+1)];
}
// Left down
if((x-1)>=0 && ((y-1)>=0))
{
// value = scr[getIndex(x-1,y+1)];
}
// Right Down
if((x+1)<tableWidth && (y+1)<tableHeight)
{
// value = scr[getIndex(x+1,y+1)];
}
// Right UP
if((x+1)<tableWidth && (y-1)>=0)
{
// value = scr[getIndex(x+1,y-1)];
}
// Left Up
if((x-1)>=0 && (y-1)>=0)
{
// value = scr[getIndex(x-1,y-1)];
}
}

getIndex(( 函数获取由 [X,Y] 指示的单元格的索引:

int getIndex(int x, int y)
{
return (tableWidth*y+x);
}