计算n×n中路径数的问题 从左上角到右下角的网格,以便路径访问 每个方块恰好一次。例如,在7×7的网格中,有111712个这样的网格 路径。
我已经编写了代码,但是它根本没有递归调用函数。 这是我得到的输出消息-
1 0
进程返回0(0x0)执行时间:2.280 s
我找不到代码无法正常工作的原因。问题出在代码的主要运动部分,而不是我从注释中找出来的优化。
#include<bits/stdc++.h>
using namespace std;
int no_of_rec_calls = 0, no_of_ways=0;
const int n=7;
int sumarr(int arr[n][n], int a)
{
int sum=0;
for(int i=0; i<a; i++)
{
for(int j=0; j<a; j++)
{
sum+=arr[i][j];
}
}
return sum;
}
void move1(int arr[n][n], int a, int row, int col)
{
no_of_rec_calls++;
/*//Optimisation 2 - in case we reach bottom right too early.
if (sumarr(arr, a)!=a*a&&row==a-1&&col==a-1)
{
return;
}*/
//When we reach the end
if (sumarr(arr, a)==a*a&&row==a-1&&col==a-1)
{
no_of_ways++;
return;
}
/*//Optimisation 3 - Hit a wall and can go only left right (not back) so cannot cover completely
if(row==0&&arr[1][col]==1)
{
return;
}
if(row==a-1&&arr[a-2][col]==1)
{
return;
}
if(col==0&&arr[row][1]==1)
{
return;
}
if(col==a-1&&arr[row][a-2]==1)
{
return;
}*/
/*//Optimisation 4 - pseudo wall case - general case of to optimisation 3
if(col!=0&&col!=a-1)
{if(arr[row][col-1]==1&&arr[row][col+1]==1)
{
return;
}}
if(row!=0&&row!=a-1)
{if(arr[row-1][col]==1&&arr[row+1][col]==1)
{
return;
}}*/
//Main movement code
if (row!=a-1)
{
if(arr[row+1][col]=0)
{
arr[row+1][col]=1;
move1(arr, a,row+1,col);
arr[row+1][col]=0;
}
}
if (col!=a-1)
{
if(arr[row][col+1]=0)
{
arr[row][col+1]=1;
move1(arr, a,row,col+1);
arr[row+1][col]=0;
}
}
if (col!=0)
{
if(arr[row][col-1]=0)
{
arr[row][col-1]=1;
move1(arr, a,row,col-1);
arr[row-1][col]=0;
}
}
if (row!=0)
{
if(arr[row-1][col]=0)
{
arr[row-1][col]=1;
move1(arr, a,row-1,col);
arr[row-1][col]=0;
}
}
return;
}
int main()
{
int arr[n][n]={0}, a=7;
arr[0][0]=1;
arr[1][0]=1;//Optimisation 1 - first move is down and we get total solutions by multiplying by 2
move1(arr,a,1,0);
cout<<no_of_rec_calls<<" "<<2*no_of_ways;
return 0;
}
我知道代码编写得不太好。我才刚刚开始学习算法。另外,除了sumarr()函数之外,有人可以建议一种更好的方法来检查我们是否到达底部吗?
谢谢