您好,我正在尝试解决编程挑战 PC/UVa ID:110102/10189,用 C 语言称为 Minesweeper。样本输入和输出:
input|output
------------
4 4 |
*... |*100
.... |2210
.*.. |1*10
.... |1110
这是我的实现:
void increment_at(int **A, int x, int y){
if (x<0 || y<0 || *(*(A+y) + x) < 0) {
return;
}
*(*(A+y) + x) += 1;
}
void mine_found(int **A, int row, int col){
*(*(A+col) + row) = -1;
int x = row-1;
int y = col-1;
increment_at(A, x, y);
x = row-1;
y = col;
increment_at(A, x, y);
x = row-1;
y = col+1;
increment_at(A, x, y);
x = row;
y = col-1;
increment_at(A, x, y);
x = row;
y = col+1;
increment_at(A, x, y);
x = row+1;
y = col-1;
increment_at(A, x, y);
x = row+1;
y = col;
increment_at(A, x, y);
x = row+1;
y = col+1;
increment_at(A, x, y);
}
int main(int argc, const char * argv[])
{
int width, height;
scanf("%d %d", &height, &width);
if (width<1 || height<1) {
return -1;
}
int i, j;
int **result = calloc(height, sizeof(int *));
for (i = 0; i<height; i++) {
*(result + i) = calloc(width, sizeof(int));
}
char *input_row = calloc(width+1, sizeof(char));
for (i = 0; i < height; i++) {
scanf("%s", input_row);
for (j = 0; j < width; j++) {
char c = *(input_row + j);
if (c == '*') {
mine_found(result, j, i);
}
}
}
free(input_row);
for (i = 0; i < height; i++) {
for (j = 0; j< width; j++) {
int cell = *(*(result+i)+j);
if (cell == -1) {
printf("*");
} else {
printf("%d",cell);
}
}
printf("\n");
}
for (i = 0; i<height; i++) {
free(*(result+i));
*(result+i)=NULL;
}
free(result);
result = NULL;
return 0;
}
有时它会给出分段错误错误。例如对于输入
3 5
...*.
.....
**...
它给Segmentation fault: 11
. 但它在输入时按预期工作:
3 3
*..
*..
...