网格中两点之间的最短路径。有一个捕获

2023-12-26

我遇到这个问题,我必须通过向右或向下移动来找到 NxM 网格中从 A 点(总是左上角)到 B 点(总是右下角)的最短路径。听起来很容易,是吗?问题是:我只能移动我现在坐在的图块上显示的数字。让我举例说明:

2 5 1 2
9 2 5 3
3 3 1 1
4 8 2 7

在这个 4x4 网格中,最短路径需要 3 步,从左上角的 2 个节点向下走到 3 个节点,从那里向右 3 个节点走到 1 个节点,然后向下 1 个节点到达目标。

[2] 5  1  2
 9  2  5  3
[3] 3  1 [1]
 4  8  2 [7]

如果不是最短路径,我也可以走这条路:

[2] 5 [1][2]
 9  2  5  3
 3  3  1 [1]
 4  8  2 [7]

不幸的是,这需要一个多达4步,因此,不符合我的利益。 这应该会让事情变得更清楚一些。现在关于输入。


用户输入网格如下:

5 4      // height and width
2 5 2 2  //
2 2 7 3  // the
3 1 2 2  // grid
4 8 2 7  //
1 1 1 1  //

Homework

我已经考虑过这一点,但无法找到比将输入的网格简化为未加权(或负权重)图表并在其上运行类似 dijkstra 或 A*(或类似的东西)的更好的解决方案。嗯...这是我迷路的部分。我一开始就实现了一些东西(或者立即扔掉一些东西)。它与 dijkstra 或 A* 或任何东西都没有关系;只是直接的广度优先搜索。


The Code

#include <iostream>
#include <vector>

struct Point;

typedef std::vector<int> vector_1D;
typedef std::vector< std::vector<int> > vector_2D;
typedef std::vector<Point> vector_point;

struct Point {
    int y, x;
    vector_point Parents;
    Point(int yPos = 0, int xPos = 0) : y(yPos), x(xPos) { }

    void operator << (const Point& point) { this->Parents.push_back(point); }
};

struct grid_t {
    int height, width;
    vector_2D tiles;

    grid_t() // construct the grid
    { 
        std::cin >> height >> width; // input grid height & width

        tiles.resize(height, vector_1D(width, 0)); // initialize grid tiles

        for(int i = 0; i < height; i++)     //
            for(int j = 0; j < width; j++)  // input each tile one at a time
                std::cin >> tiles[i][j];    // by looping through the grid
    }
};

void go_find_it(grid_t &grid)
{
    vector_point openList, closedList;
    Point previous_node; // the point is initialized as (y = 0, x = 0) if not told otherwise
    openList.push_back(previous_node); // (0, 0) is the first point we want to consult, of course

    do
    {
        closedList.push_back(openList.back()); // the tile we are at is good and checked. mark it so.
        openList.pop_back(); // we don't need this guy no more

        int y = closedList.back().y; // now we'll actually
        int x = closedList.back().x; // move to the new point

        int jump = grid.tiles[y][x]; // 'jump' is the number shown on the tile we're standing on.

        if(y + jump < grid.height) // if we're not going out of bounds
        { 
            openList.push_back(Point(y+jump, x)); // 
            openList.back() << Point(y, x); // push in the point we're at right now, since it's the parent node
        }
        if(x + jump < grid.width) // if we're not going out of bounds
        { 
            openList.push_back(Point(y, x+jump)); // push in the new promising point
            openList.back() << Point(y, x); // push in the point we're at right now, since it's the parent node
        }
    }
    while(openList.size() > 0); // when there are no new tiles to check, break out and return
}

int main()
{
    grid_t grid; // initialize grid

    go_find_it(grid); // basically a brute-force get-it-all-algorithm

    return 0;
}

我或许还应该指出,运行时间不能超过 1 秒,最大网格高度和宽度为 1000。所有图块也是从 1 到 1000 的数字。

Thanks.


编辑后的代码

#include <iostream>
#include <vector>

struct Point;

typedef std::vector<int> vector_1D;
typedef std::vector< std::vector<int> > vector_2D;
typedef std::vector<Point> vector_point;

struct Point {
    int y, x, depth;
    vector_point Parents;
    Point(int yPos = 0, int xPos = 0, int dDepth = 0) : y(yPos), x(xPos), depth(dDepth) { }

    void operator << (const Point& point) { this->Parents.push_back(point); }
};

struct grid_t {
    int height, width;
    vector_2D tiles;

    grid_t() // construct the grid
    { 
        std::cin >> height >> width; // input grid height & width

        tiles.resize(height, vector_1D(width, 0)); // initialize grid tiles

        for(int i = 0; i < height; i++)     //
            for(int j = 0; j < width; j++)  // input each tile one at a time
                std::cin >> tiles[i][j];    // by looping through the grid
    }
};

int go_find_it(grid_t &grid)
{
    vector_point openList, closedList;
    Point previous_node(0, 0, 0); // the point is initialized as (y = 0, x = 0, depth = 0) if not told otherwise
    openList.push_back(previous_node); // (0, 0) is the first point we want to consult, of course

    int min_path = 1000000;

    do
    {
        closedList.push_back(openList[0]); // the tile we are at is good and checked. mark it so.
        openList.erase(openList.begin()); // we don't need this guy no more

        int y = closedList.back().y; // now we'll actually move to the new point
        int x = closedList.back().x; //
        int depth = closedList.back().depth; // the new depth

        if(y == grid.height-1 && x == grid.width-1) return depth; // the first path is the shortest one. return it

        int jump = grid.tiles[y][x]; // 'jump' is the number shown on the tile we're standing on.

        if(y + jump < grid.height) // if we're not going out of bounds
        { 
            openList.push_back(Point(y+jump, x, depth+1)); // 
            openList.back() << Point(y, x); // push in the point we're at right now, since it's the parent node
        }
        if(x + jump < grid.width) // if we're not going out of bounds
        { 
            openList.push_back(Point(y, x+jump, depth+1)); // push in the new promising point
            openList.back() << Point(y, x); // push in the point we're at right now, since it's the parent node
        }
    }
    while(openList.size() > 0); // when there are no new tiles to check, break out and return false

    return 0;
}

int main()
{
    grid_t grid; // initialize grid

    int min_path = go_find_it(grid); // basically a brute-force get-it-all-algorithm

    std::cout << min_path << std::endl;
    //system("pause");
    return 0;
}

程序现在打印出正确的答案。现在我必须优化(运行时间太大)。关于这个有什么提示吗?优化是我最讨厌的一件事。


答案

最后,该解决方案似乎只包含很少的代码。越少越好,因为我喜欢。感谢 Dejan Jovanović 提供了完美的解决方案

#include <iostream>
#include <vector>
#include <algorithm>

struct grid_t {
    int height, width;
    std::vector< std::vector<int> > tiles;
    std::vector< std::vector<int> > distance;

    grid_t() // construct the grid
    { 
        std::cin >> height >> width; // input grid height & width

        tiles.resize(height, std::vector<int>(width, 0)); // initialize grid tiles
        distance.resize(height, std::vector<int>(width, 1000000)); // initialize grid tiles

        for(int i = 0; i < height; i++)     //
            for(int j = 0; j < width; j++)  // input each tile one at a time
                std::cin >> tiles[i][j];    // by looping through the grid
    }
};

int main()
{
    grid_t grid; // initialize grid

    grid.distance[0][0] = 0;
    for(int i = 0; i < grid.height; i++) {
        for(int j = 0; j < grid.width; j++) {
            if(grid.distance[i][j] < 1000000) {
                int d = grid.tiles[i][j];
                if (i + d < grid.height) {
                    grid.distance[i+d][j] = std::min(grid.distance[i][j] + 1, grid.distance[i+d][j]);
                }
                if (j + d < grid.width) {
                    grid.distance[i][j+d] = std::min(grid.distance[i][j] + 1, grid.distance[i][j+d]);
                }
            }
        }
    }
    if(grid.distance[grid.height-1][grid.width-1] == 1000000) grid.distance[grid.height-1][grid.width-1] = 0;
    std::cout << grid.distance[grid.height-1][grid.width-1] << std::endl;
    //system("pause");
    return 0;
}

需要构建图表,这可以通过使用矩阵一次扫描的动态规划轻松解决。

您可以在开始时将距离矩阵 D[i,j] 设置为 +inf,其中 D[0,0] = 0。在遍历矩阵时,您只需执行以下操作

if (D[i,j] < +inf) {
  int d = a[i, j];
  if (i + d < M) {
    D[i + d, j] = min(D[i,j] + 1, D[i + d, j]);
  }
  if (j + d < N) {
    D[i, j + d] = min(D[i,j] + 1, D[i, j + d]);
  }
}

最终的最小距离在 D[M -1, N-1] 中。如果您希望重建路径,您可以保留一个单独的矩阵来标记最短路径的来源。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

网格中两点之间的最短路径。有一个捕获 的相关文章

  • Caliburn.Micro - ShowDialog() 如何关闭对话框?

    EDIT 新信息 刚刚设法让记录器工作 老实说 我不知道 cm 有一个 并且在尝试使用时收到此消息TryClose TryClose requires a parent IConductor or a view with a Close m
  • 如何在特定时间以毫秒精度触发 C# 函数?

    我有两台计算机 它们的时间通过 NTP 同步 确保时间仅相差几毫秒 其中一台计算机将通过 TCP 向另一台计算机发送一条消息 以在两台计算机上的未来指定时间启动某个 c 函数 我的问题是 如何在特定时间以毫秒精度 或更好 触发 C 中的函数
  • 使用 Json.NET 序列化子类

    我正在尝试使用 Json NET 序列化子类 生成的 json 包含超类的序列化属性 但是not子类对象的属性 这似乎与我发现的一个问题有关这里就这样 https stackoverflow com q 5863496 498969 但必须
  • STL之类的容器typedef快捷方式?

    STL 容器的常见模式是这样的 map
  • NDK 应用 onDestroy 清理 - 如何 DetachCurrentThread

    因此 如果我们连接 我们必须在完成后分离线程 对吗 JNIEnv get jni env JNIEnv res JAVA VM gt GetEnv void res JNI VERSION 1 6 Using cached JavaVM J
  • 使用 C# 将多个音频样本混合到单个文件中

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在寻找一个能够创建音频文件 mp3 或 wav 的库 NAudio http www codeple
  • ContentDialog 未与 UWP 中心对齐

    据我所知 ContentDialog的默认行为应该是使其在 PC 上居中并在移动设备上与顶部对齐 但就我而言 即使在 PC 上我也将其与顶部对齐 但我不明白发生了什么 我正在使用代码隐藏来创建它 这是我正在使用的代码片段 Creates t
  • 组合框下拉位置

    我有一个最大化的表单 其中包含 500px 的组合框控件 停靠在右上角 Width 尝试打开组合框后 列表的一半超出了屏幕 如何强制列表显示在表单中 棘手的问题 我找不到解决这个问题的好办法 只是一个解决方法 添加一个新类并粘贴如下所示的代
  • 在Python中确定句子中2个单词之间的邻近度

    我需要确定 Python 句子中两个单词之间的接近度 例如 在下面的句子中 the foo and the bar is foo bar 我想确定单词之间的距离foo and bar 确定之间出现的单词数foo and bar 请注意 该词
  • 对作为函数参数传递的指针使用删除

    删除作为函数参数传递的指针是否可以 并且合法 如下所示 include
  • .NET 5 EF Core SaveChangesAsync 因错误而挂起

    尽管这个问题有很多结果 但没有一个真正给我明确的答案 每次我尝试通过 AddAsync 和 SaveChangesAsync 方法插入错误数据 例如重复的主键 时 我都会看到以下日志 执行 DbCommand 失败 15 毫秒 我还在 SQ
  • 在c#中获取没有时间的日期

    我的表上有一列 缺勤日期时间 日期 当我想要获取包含日期的行时 它返回 0 行 这是我的 C 代码 DateTime ClassDate DateTime Parse lblDate Content ToString var Abs dbs
  • 调用异步方法在视图模型的构造函数中加载数据有警告

    我的视图包含一个 ListView 它显示来自互联网的一些数据 我创建一个异步方法来加载数据并在我的视图模型的构造函数中调用该方法 它有一个警告提示我现在使用await关键字 还有其他解决方案可以在构造函数中异步加载数据吗 有几种可以应用的
  • 配置:错误:无法运行C编译的程序

    我正在尝试使用 Debian Wheezy 操作系统在我的 Raspberry Pi 上安装不同的软件 当我运行尝试配置软件时 我尝试安装我得到此输出 checking for C compiler default output file
  • 如何同步nosql db(ravendb)中的更改

    我已经开始在 RavenDB 的示例上学习 NoSQL 我从一个最简单的模型开始 假设我们有由用户创建的主题 public class Topic public string Id get protected set public stri
  • C++ 中是否有与 PHP 的explode() 函数等效的函数? [复制]

    这个问题在这里已经有答案了 可能的重复 在 C 中分割字符串 https stackoverflow com questions 236129 splitting a string in c 在 PHP 中 explode 函数将获取一个字
  • 具有四个 && 的 LINQ Where 子句

    我正在尝试在Where 子句中创建一个带有4 个参数的LINQ 查询 这是一个 Windows 8 应用程序项目 我正在使用 SQLite 数据库 SQLite 实现 https github com praeclarum sqlite n
  • 从对列表创建邻接列表类型结构

    在 C 中 我有 class Pair int val1 int val2 我有一个来自以下来源的配对列表 List
  • 为什么在构造函数中设置字段是(或不是)线程安全的?

    假设您有一个像这样的简单类 class MyClass private readonly int a private int b public MyClass int a int b this a a this b b public int
  • 将一个 IEnumerable 拆分为多个 IEnumerable

    我是 linq 新手 我需要根据指示器将 Couple string text bool Indicator 类型的 IEnumerable 拆分为多个 IEnumerable 我尝试使用skipWhile 和 TakeWhile 但没有找

随机推荐