题目地址:点击打开链接
思路:上来就是无脑敲代码,结果敲了一个超内存的,仔细一想,就算不超内存,时间也会超时,每次走过的不能标记,因为以后还要再次走,这是计数,仔细一想种类数都是long long 类型的了,要搜出来早超时了,参考大神的代码写出了记忆化搜索代码
错误代码:
#include <iostream> #include<cstring> #include<queue> using namespace std; struct board { int x,y; }cf[1600]; int map[40][40]; int n,sum,endi,endj; int dir[2][2] = {{1,0},{0,1}}; bool check(int x,int y) { if(x >= 0 && x < n && y >= 0 && y < n && (map[x][y] || (!map[x][y] && x == n-1 && y == n-1))) return true; return false; } void bfs() { int i; queue<board> q; board in,out; in.x = 0; in.y = 0; q.push(in); while(!q.empty()) { out = q.front(); q.pop(); if(out.x == n-1 && out.y == n-1) { sum++; } else { for(i=0; i<2; i++) { in.x = out.x + dir[i][0] * map[out.x][out.y]; in.y = out.y + dir[i][1] * map[out.x][out.y]; if(check(in.x,in.y)) { q.push(in); } } } } } int main() { int i,j,l; char lol[35]; while(cin>>n && n != -1) { sum = 0; l = 0; for(i=0; i<n; i++) { cin>>lol; for(j=0; j<n; j++) { map[i][j] = lol[j] - '0'; cf[l].x = i; cf[l].y = j; l++; } } bfs(); cout<<sum<<endl; } return 0; }
AC代码1:
dp[x][y]记录的是点(x,y)到点(n-1,n-1)的数量,dp[x][y]的数量可以由它所到达的点的dp[x][y]的和求出来
#include <iostream> #include<cstring> #include<cstdio> using namespace std; int map[40][40]; long long dp[40][40];//用long long 类型 int dir[2][2] = {{1,0},{0,1}}; int n; long long dfs(int x,int y)//返回值是long long 类型 { int newx,newy,i; if(dp[x][y] || !map[x][y])//map[x][y]为0时,肯定没有到点(n-1,n-1)的路径,直接返回dp[x][y],此时dp[x][y]为0 return dp[x][y]; for(i=0; i<2; i++) { newx = x + dir[i][0] * map[x][y]; newy = y + dir[i][1] * map[x][y]; if(newx >= 0 && newy >= 0 && newx < n && newy < n)//判断条件写清楚 dp[x][y] += dfs(newx,newy); } return dp[x][y]; } int main() { int i,j; char lol[35]; while(cin>>n && n != -1) { memset(dp,0,sizeof(dp)); for(i=0; i<n; i++) { cin>>lol; for(j=0; j<n; j++) { map[i][j] = lol[j] - '0'; } } dp[n-1][n-1] = 1; //printf("%I64d\n",dfs(0,0)); cout<<dfs(0,0)<<endl; } return 0; }
AC代码2:
#include <iostream> #include<cstring> using namespace std; int map[40][40]; long long dp[40][40];//用long long 类型 int dir[2][2] = {{1,0},{0,1}}; int main() { int i,j,n; char lol[35]; while(cin>>n && n != -1) { memset(dp,0,sizeof(dp)); for(i=0; i<n; i++) { cin>>lol; for(j=0; j<n; j++) { map[i][j] = lol[j] - '0'; } } dp[0][0] = 1; for(i=0; i<n; i++) { for(j=0; j<n; j++) { if(!map[i][j] || !dp[i][j]) { continue; } if(i + map[i][j] < n) dp[i+map[i][j]][j] += dp[i][j]; if(j + map[i][j] < n) dp[i][j+map[i][j]] += dp[i][j]; } } cout<<dp[n-1][n-1]<<endl; } return 0; }