所以问题是关于打印矩阵左上角到右下角的所有路径。允许的移动是向下,向右和对角线。必须使用障碍物,即如果存在障碍物,则不应打印该路径。
所以我写了这段代码,如果运行输出是
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。
有任何想法吗?
TIA
#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 grid\n");
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 offsets\n");
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 are\n");
printAll(*mat, n);
}
最佳答案
要获得正确的输出,请将paths()
函数的for循环更改为:
for(k = i; k < n; k++)
{path[val + k - j] = *((mat + i*n) + k);}
关于c - 带有障碍物的矩阵中的路径数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44558759/