我想编写一个数独求解器。用户将需要传递9个argv来启动像这样的数独板:
./a.out "9...7...." "2...9..53" ".6..124.." etc..
我正在寻找一种简单的方法来用传递的参数填充此类数组:
int grille[9][9] = {
{9,0,0,1,0,0,0,0,5},
{0,0,5,0,9,0,2,0,1},
{8,0,0,0,4,0,0,0,0},
{0,0,0,0,8,0,0,0,0},
{0,0,0,7,0,0,0,0,0},
{0,0,0,0,2,6,0,0,9},
{2,0,0,3,0,0,0,0,6},
{0,0,0,2,0,0,9,0,0},
{0,0,1,9,0,4,5,7,0}
};
我该如何进行?我需要malloc
吗?
答案 0 :(得分:2)
您不需要malloc
来分配网格,只需在main
函数中将其定义为局部变量即可。您需要从命令行字符串参数初始化此对象。
这是一个简单的函数,用于初始化2D数组的单行:
void init_row(int *row, const char *s) {
int i;
for (i = 0; i < 9; i++) {
row[i] = 0;
}
if (s) {
for (i = 0; i < 9 && s[i]; i++) {
if (s[i] >= '1' && s[i] <= '9')
row[i] = s[i] - '0';
}
}
}
您可以通过以下方式初始化整个网格:
#include <stdio.h>
int main(int argc, char *argv[]) {
int grille[9][9];
int i, j;
/* initialize the grid */
for (i = 0; i < 9; i++) {
init_row(grille[i], i + 1 < argc ? argv[i + 1] : NULL);
}
/* output the grid */
for (i = 0; i < 9; i++) {
for (j = 0; j < 9; j++) {
putchar(".123456789"[grille[i][j]]);
}
putchar('\n');
}
return 0;
}