同时,我终于设法将想法 2 转换为工作代码。我没有使用矩阵a
进行路径回溯,因为它不是必需的。它仍然相当复杂,所以如果有人有更优雅的解决方案,请发布!
#include <stdio.h>
#include <string.h>
void PrintAllPaths(int **a, int M, int N, int x, int y) {
static char Path[500]="(0,0)"; //keeps path for currently processed recursion
static int m=M, n=N; //keep initial values of M and N
static bool passedXY=false; //have we passed (x,y) along current path?
if ((x<0 || y<0) && (passedXY==false)) { return;} //missed (X,Y), so skip
if (x==0 && y==0) passedXY=true;
if ((M==1 && N==1)) {puts(Path); return;}; //we have made N-1 steps down and M-1 steps right, so we reached (M-1,N-1) and we print path
//try to go right
if (N>1) {
char temp[10];
sprintf(temp,"(%d,%d)",m-M,n-N+1); //add point to the right to the path
strcat(Path,temp);
PrintAllPaths(a, M, N-1, x, y-1); //go right
Path[strlen(Path)-5]='\0'; //remove last point from the path, since it is processed
if ((x>0 && y>=0)||(x>=0 && y>0)) passedXY=false; //reset passedXY value if needed
};
//try to go down
if (M>1) {
char temp[10];
sprintf(temp,"(%d,%d)",m-M+1,n-N);
strcat(Path,temp);
PrintAllPaths(a, M-1, N, x-1, y);
Path[strlen(Path)-5]='\0';
if ((x>0 && y>=0)||(x>=0 && y>0)) passedXY=false;
}
};
int main() {
int **a=0;
PrintAllPaths(a, 3, 3, 1, 2);
char ch='a'; scanf("%c",ch);
}