C语言中,如何描述“遍历二维数组某一格周围格子”?
发布网友
发布时间:2023-11-12 10:37
我来回答
共3个回答
热心网友
时间:2024-11-18 10:31
int dir[8][2] = {
-1, 0,
1, 0,
0, 1,
0, -1,
-1, -1,
-1, 1,
1, -1,
1, 1};
int x, y, i, next_x, next_y;
/*然后设当前位置为第x行第y列,一共n行m列,行号列号从0开始到n-1和m-1*/
for (i = 0; i < 8; i ++)
{
next_x = x + dir[i][0];
next_y = y + dir[i][1];
if (next_x < 0 || next_x >= n || next_y < 0 || next_y >= m) /*这里判断next_x和next_y是不是在行号/列号的范围内,如果不在的话*/
continue; /*这一组next_x和next_y就不处理*/
/*这里第next_x行,next_y列就是第x行第y列的周围某个格子*/
}
热心网友
时间:2024-11-18 10:31
假如二维数组是a[M][N]的话,首先通过角标判断是在中间还是边上还是角上,然后改变角标,遍历就行了。假如要遍历周围格子的那一格为a[i][j]
if (i == 0 & j == 0)
//遍历 a[i+1][j], a[i][j+1], a[i+1][j+1]
else if (i == 0 & j == N-1)
//遍历 a[i][j-1], a[i+1][j], a[i-1][j-1]
else if (i == M-1 & j == 0)
//遍历 a[i-1][j], a[i][j+1], a[i-1][j+1]
else if (i == M-1 & j == N-1)
//遍历 a[i][j-1], a[i-1][j], a[i-1][j-1]
else if (i == 0 & j != 0 & j != N-1)
//遍历 a[i][j-1], a[i][j+1], a[i+1][j], a[i+1][j-1], a[i+1][j+1]
else if (i == M-1 & j != 0 & j != N-1)
//遍历 a[i][j-1], a[i][j+1], a[i-1][j], a[i-1][j-1], a[i-1][j+1]
else if (j == 0 & i != 0 & i != M-1)
//遍历 a[i-1][j], a[i+1][j], a[i][j+1], a[i-1][j+1], a[i+1][j+1]
else if (j == N-1 & i != 0 & i != M-1)
//遍历 a[i-1][j], a[i+1][j], a[i][j-1], a[i-1][j-1], a[i+1][j-1]
else
//遍历 a[i-1][j], a[i+1][j], a[i][j-1], a[i][j+1], a[i-1][j-1], a[i+1][j-1], a[i-1][j+1], a[i+1][j+1]
热心网友
时间:2024-11-18 10:32
设当前位置为i,j,周围的格子分别+1,-1不就是了吗,当然这中间需要判断是否小于0,以及是否大于数组长度(一维与二维都要判断)