我目前正在练习递归,这样我就可以在Tideman CS50问题中使用它.具体地说,我想学习如何使用递归遍历矩阵(2D数组).
出于练习目的,我已经创建了一个简单的3x32D数组,我想打印该数组的内容.
不幸的是,my logic breaks after the first row is successfully printed: printing subsequent elements of the array is incorrect岁.更准确地说,我的递归函数在try 打印位置为i = 1
,j = 0
的元素时"中断".我想知道为什么会发生这种情况.
代码:
#include <stdio.h>
void recursive_print(int lenght, int i, int j, int array[i][j]);
int main(void)
{
int lenght = 3;
int i = 0;
int j = 0;
int array[lenght][lenght];
array[0][0] = 0;
array[0][1] = 1;
array[0][2] = 2;
array[1][0] = 3;
array[1][1] = 4;
array[1][2] = 5;
array[2][0] = 6;
array[2][1] = 7;
array[2][2] = 8;
recursive_print(lenght, i, j, array);
return 0;
}
void recursive_print(int lenght, int i, int j, int array[i][j])
{
// Base case
if (i == lenght - 1 && j == lenght - 1)
{
printf("Base case\n");
printf("%i\n", array[i][j]);
}
// Recursive case(s)
else if (j == lenght - 1)
{
printf("Recursive case 1\n");
printf("%i\n", array[i][j]);
recursive_print(lenght, i + 1, j - j, array);
}
else
{
printf("Recursive case 2\n");
printf("%i\n", array[i][j]);
recursive_print(lenght, i, j + 1, array);
}
}
实际yields :
Recursive case 2
0
Recursive case 2
1
Recursive case 1
2
Recursive case 2
0
Recursive case 2
2
Recursive case 1
4
Recursive case 2
0
Recursive case 2
3
Base case
6
预期输出:
Recursive case 2
0
Recursive case 2
1
Recursive case 1
2
Recursive case 2
3
Recursive case 2
4
Recursive case 1
5
Recursive case 2
6
Recursive case 2
7
Base case
8