gpt4 book ai didi

c - 编程查找二维数组中的相邻单元格

转载 作者:行者123 更新时间:2023-11-30 18:58:21 25 4
gpt4 key购买 nike

请分享一些查找二维数组的所有相邻单元格的逻辑。我有两个逻辑,但我仍然在寻找第三个最好的逻辑。

1).遍历所有单元格并检查是否与所选单元格相邻。

2).通过计算索引直接跳转到相邻单元格。我发现这种方法比第一种方法更好,但有一点我不喜欢它有很多很多 if 条件?

-布佩什

最佳答案

从 max(0, x-1) 和 max(0, y-1) 循环到 min(x+1, MAX_X) 和 min(y+1, MAX_Y) 并跳过 (x,y)。

例如:

#include <stdio.h>
#include <stdlib.h>

int max(int a, int b) {
if (a > b) {
return a;
}
else {
return b;
}
}

int min(int a, int b) {
if (a < b) {
return a;
}
else {
return b;
}
}

void print_adjacent(int x, int y, int cols, int rows) {
int lowest_x = max(x-1, 0);
int highest_x = min(x+1, cols-1);
int lowest_y = max(y-1, 0);
int highest_y = min(y+1, rows-1);
int i, j;

for ( i = lowest_x; i <= highest_x; i++ ) {
for ( j = lowest_y; j <= highest_y; j++ ) {
if ( !(i == x && j == y) ) {
printf("(%d, %d) is adjacent to (%d, %d)\n", i, j, x, y);
}
}
}
}

int main(void) {
int num_cols = 10;
int num_rows = 10;

print_adjacent(0, 0, num_cols, num_rows);
print_adjacent(0, 3, num_cols, num_rows);
print_adjacent(4, 5, num_cols, num_rows);
print_adjacent(9, 5, num_cols, num_rows);
print_adjacent(9, 9, num_cols, num_rows);

return EXIT_SUCCESS;
}

关于c - 编程查找二维数组中的相邻单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17133442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com