小U的最大连续移动次数问题 | 豆包MarsCode AI刷题

18 阅读1分钟
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

int solution(int m, int n, vector<vector<int>> &a) {
  // 初始化visited数组
  vector<vector<bool>> visited(m, vector<bool>(n, false));

  // 定义DFS函数
  function<int(int, int, bool)> dfs = [&](int x, int y, bool isUp) -> int {
    // 标记当前位置为已访问
    visited[x][y] = true;

    int maxPath = 0;

    // 尝试向四个方向移动
    vector<pair<int, int>> directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    for (auto &dir : directions) {
      int nx = x + dir.first;
      int ny = y + dir.second;

      // 检查边界和是否已访问
      if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visited[nx][ny]) {
        // 检查是否满足上坡或下坡条件
        if ((isUp && a[nx][ny] < a[x][y]) || (!isUp && a[nx][ny] > a[x][y])) {
          // 递归调用DFS
          maxPath = max(maxPath, dfs(nx, ny, !isUp));
        }
      }
    }

    // 回溯:标记当前位置为未访问
    visited[x][y] = false;

    // 返回当前路径长度
    return maxPath + 1;
  };

  int maxSteps = 0;

  // 遍历地图中的每个位置,尝试从该位置开始DFS
  for (int i = 0; i < m; ++i) {
    for (int j = 0; j < n; ++j) {
      maxSteps = max(maxSteps, dfs(i, j, true));
      maxSteps = max(maxSteps, dfs(i, j, false));
    }
  }

  return maxSteps - 1;
}

int main() {
  vector<vector<int>> a1 = {{1, 2}, {4, 3}};
  cout << (solution(2, 2, a1) == 3) << endl;

  vector<vector<int>> a2 = {{10, 1, 6}, {5, 9, 3}, {7, 2, 4}};
  cout << (solution(3, 3, a2) == 8) << endl;

  vector<vector<int>> a3 = {
      {8, 3, 2, 1}, {4, 7, 6, 5}, {12, 11, 10, 9}, {16, 15, 14, 13}};
  cout << (solution(4, 4, a3) == 11) << endl;
}