HDU-1078.FatMouseandCheese(线性dp + dfs)

  本题大意:在一个n * n的迷宫内进行移动,左上角为初始位置,每次可以走的步数不能超过m,并且每次走的方格上面的数字要大于前一次走的放个数字,不能走到格子外面,问如何能使得到的数字和最大。

  本题思路:dfs记忆化搜即可。

  参考代码:

 1 #include <iostream>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 int n, m;
 7 const int maxn = 1e2 + 5;
 8 int maze[maxn][maxn], dp[maxn][maxn], dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
 9 
10 int dfs(int x, int y) {
11     int ans = 0;
12     if(!dp[x][y]) {
13         for(int i = 1; i <= m; i ++) {
14             for(int j = 0; j < 4; j ++) {
15                 int dx = x + dir[j][0] * i;
16                 int dy = y + dir[j][1] * i;
17                 if(dx < 1 || dy < 1 || dx > n || dy > n) continue;
18                 if(maze[dx][dy] > maze[x][y]) ans = max(ans, dfs(dx, dy));
19             }
20         }
21         dp[x][y] = ans + maze[x][y];
22     }
23     return dp[x][y];
24 }
25 
26 int main () {
27     ios :: sync_with_stdio (false);
28     while(cin >> n >> m) {
29         memset(dp, 0, sizeof dp);
30         if(n == -1 && m == -1) break;
31         for(int i = 1; i <= n; i ++)
32             for(int j = 1; j <= n; j ++)
33                 cin >> maze[i][j];
34         cout << dfs(1, 1) << endl;    
35     }
36     return 0;
37 }
View Code
原文地址:https://www.cnblogs.com/bianjunting/p/10653285.html