我使用类似的方法来Adjacent Mines
获取Minesweeper Game
. 我所做的是,我使用了这样的数组 (MAX_NUMBER_OF_CELLS = 8):
int offset[MAX_NUMBER_OF_CELLS][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
考虑到我们正在讨论矩阵中的CELL
at location 0, 0
。我们将简单地添加这些偏移值,CELL
以检查相邻的 CELL 是否是有效的 CELL(即它落在矩阵内)。如果它是VALID,那么我们将查看它是否包含1
,如果是而不是sum
通过1
否则不增加。
//rest of the values represent x and y that we are calculating
(-1, -1) (-1, 0) (-1, 1)
-------------------------
(0, -1) |(0, 0(This is i and j))| (0, 1)
-------------------------
(1, -1) (1, 0) (1, 1)
sum = 0;
for (k = 0; k < MAX_NUMBER_OF_CELLS; k++)
{
indexX = i + offset[k][0];
indexY = j + offset[k][1];
if (isValidCell(indexX, indexY, model)) // Here check if new CELL is VALID
// whether indexX >= 0 && indexX < rows
// and indexY >= 0 && indexY < columns
{
flag = 1;
if (arr[indexX][indexY] == 1))
sum += 1;
}
}
编辑 1:
这是一个工作示例(C 不是我的语言,尽管我仍然尝试使用它来给你一个想法:-)):
#include <stdio.h>
#include <stdlib.h>
int findAdjacent(int [4][4], int, int, int, int);
int main(void)
{
int arr[4][4] = {
{0, 1, 0, 0},
{1, 0, 1, 1},
{0, 1, 0, 0},
{0, 0, 0, 0}
};
int i = 2, j = 2;
int sum = findAdjacent(arr, i, j, 4, 4);
printf("Adjacent cells from (%d, %d) with value 1 : %d\n", i, j, sum);
return EXIT_SUCCESS;
}
int findAdjacent(int arr[4][4], int i, int j, int rows, int columns)
{
int sum = 0, k = 0;
int x = -1, y = -1; // Location of the new CELL, which
// we will find after adding offsets
// to the present value of i and j
int offset[8][2] = {
{-1, -1},
{-1, 0},
{-1, 1},
{0, -1},
{0, 1},
{1, -1},
{1, 0},
{1, 1}
};
for (k = 0; k < 8; k++)
{
x = i + offset[k][0];
y = j + offset[k][1];
if (isValidCell(x, y, rows, columns))
{
if (arr[x][y] == 1)
sum += 1;
}
}
return sum;
}
int isValidCell(int x, int y, int rows, int columns)
{
if ((x >= 0 && x < rows) && (y >= 0 && y < columns))
return 1;
return 0;
}