所以问题是关于打印矩阵从左上角到右下角的所有路径。 允许的移动是向下、向右和对角线。 这必须应用于障碍物,即如果存在障碍物,则不应打印该路径。所以我写了这段代码,如果运行输出是
1 4 7 8 9
1 4 5 8 9
1 4 5 8 9
1 4 5 9
1 4 8 9
1 5 8 9
1 5 8 9
1 5 9
第 3 行和第 7 行的最后一秒值需要为 6。但相反,它是 8。有什么想法吗?蒂亚
#include<stdio.h>
#include<stdlib.h>
void paths(int *mat, int i, int j, int n, int *path, int val)
{
int k,l;
if (i == n - 1)
{
for(k = j; k < n; k++)
{path[val + k - j] = *((mat + i*n) + k);}
for(l = 0; l < val + n - j; l++)
{if(path[l] == 0){return;}}
for(l = 0; l < val + n - j; l++)
{
printf("%d ", path[l]);
}printf("n");
return;
}
if (j == n - 1)
{
for(k = j; k < n; k++)
{path[val + k - i] = *((mat + k*n) + j);}
for(l = 0; l < val + n - j; l++)
{if(path[l] == 0){return;}}
for(l = 0; l < val + n - i; l++)
{
printf("%d ", path[l]);
}printf("n");
return;
}
path[val] = *((mat + i*n) + j);
paths(mat, i+1, j, n, path, val+1);
paths(mat, i, j+1, n, path, val+1);
paths(mat, i+1, j+1, n, path, val+1);
}
void printAll(int *mat, int n)
{
int *path = malloc((2*n) * sizeof(int));
paths(mat, 0, 0, n, path, 0);
}
int main()
{
int n,i,j;
printf("Enter the size of the gridn");
scanf("%d", &n);
int mat[n][n];
int count = 1;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
mat[i][j] = count; count = count + 1;
}
}
printf("Enter the grid points that are offsetsn");
int obs[n*n][2];i=0;
while(1 == 1)
{
scanf("%d%d", &obs[i][0], &obs[i][1]);
mat[obs[i][0]][obs[i][1]] = 0;
if(obs[i][0] == -1 || obs[i][1] == -1){break;}
i = i + 1;
}
printf("The paths for the robot aren");
printAll(*mat, n);
}
要获得正确的输出,请将 paths()
函数的 for 循环更改为:
for(k = i; k < n; k++)
{path[val + k - j] = *((mat + i*n) + k);}