山再高,往上爬,总能登顶;
路再长,走下去,定能到达。
UPC-迷宫
问题描述
晚上,跑男们来了节目的最后一站:江苏省扬州中学,完成最后一项比赛:撕名牌。撕名牌的地点是一个由nn房间组成的正方形,每个房间里都有一个数字,表示从这个房间可以通过地道向右或向下穿过几个房间。从左上角开始,如果谁能安全到达右下角就算胜利。
这里44的方格中每一格表示进入这个房间时,队员可以向右或向下穿过的房间数。
郑恺是奔跑小王子,当他拿到这张地图时,脸都变绿了,速度再快,进了迷宫一样的房间也是没办法啊,还好参加JSOI2015夏令营的小伙伴都在,你能帮帮他算出从左上角可以到达右下角的路径数目吗?
输入
第一行为一个整数n,表示棋盘的大小。
以下有n行,每行有n个数字(数字与数字之间有一个空格隔开),表示在相应的格子内,棋子可以向右或向下跳跃的格子数。
输出
输出共一行,包含一个数,表示从左上角可以到达右下角的路径数目。
Sample Input
4
2 3 3 1
1 2 1 3
1 2 3 1
3 1 1 0
Sample Output
3
思路分析
最开始我想用dfs直接搜索的,但是没想到内存超限了。
然后冷静一分析,这不就是一个基础动态规划吗??只不过我这次从前往后传状态而不是从后往前访问状态了。
这里有个坑点,如果说当前点是0的话你无论右走还是下走都是当前点,所以这个时候的点就不能走。
AC时间到
#include<algorithm>
#include<iostream>
#include<string.h>
#include <iomanip>
#include<stdio.h>
#include<utility>
#include<vector>
#include<string>
#include<math.h>
#include<cmath>
#include<queue>
#include<stack>
#include<deque>
#include<map>
#pragma warning(disable:4244)
#define PI 3.1415926536
#pragma GCC optimize(2)
#define accelerate cin.tie(NULL);cout.tie(NULL);ios::sync_with_stdio(false);
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll ll_inf = 9223372036854775807;
const int int_inf = 2147483647;
const short short_inf = 32767;
const char char_inf = 127;
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
inline ll read() {
ll c = getchar(), Nig = 1, x = 0;
while (!isdigit(c) && c != '-')c = getchar();
if (c == '-')Nig = -1, c = getchar();
while (isdigit(c))x = ((x << 1) + (x << 3)) + (c ^ '0'), c = getchar();
return Nig * x;
}
inline void out(ll a) {
if (a < 0)putchar('-'), a = -a;
if (a >= 10)out(a / 10);
putchar(a % 10 + '0');
}
ll qpow(ll x, ll n, ll mod) {
ll res = 1;
while (n > 0) {
if (n & 1)res = (res * x) % mod;
x = (x * x) % mod;
n >>= 1;
}
return res;
}
#define Floyd for(int k = 1; k <= n; k++)for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)
#define read read()
int save[500][500];
int dp[500][500];
int main()
{
int n = read;
dp[1][1] = 1;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
save[i][j] = read;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
{
if (save[i][j])//当前不为0
{
if (i + save[i][j] <= n)dp[i + save[i][j]][j] += dp[i][j];//往下走
if (j + save[i][j] <= n)dp[i][j + save[i][j]] += dp[i][j];//往右走
}
}
cout << dp[n][n] << endl;
}
By-轮月