【问题标题】:shortest path in two-dimensional array using C使用C的二维数组中的最短路径
【发布时间】:2016-06-06 15:15:57
【问题描述】:

我想找到从 (0,0) 到 (6,6) 的最短路径,但我不知道如何使用 C。-1 是我可以走的路,-2 是我可以走的路我不能去。 0 是起点,-3 是终点。 请帮忙..

#include<stdio.h>

#define VERTICES 7

int maze[VERTICES][VERTICES] = {
{  0, -2, -1, -1, -1, -1, -1 },
{ -1, -2, -1, -2, -2, -2, -2 },
{ -1, -1, -1, -1, -1, -1, -1 },
{ -1, -2, -2, -2, -2, -2, -1 },
{ -1, -2, -1, -1, -1, -2, -1 },
{ -1, -2, -1, -2, -2, -2, -1 },
{ -1, -1, -1, -2, -1, -1, -3 } };

int A[VERTICES][VERTICES];

printA(int n)
{
int i, j;
printf("===============================\n");
for (i = 0; i < n; i++){
    for (j = 0; j < n; j++)
        printf("%3d", A[i][j]);
    printf("\n");
}
printf("===============================\n");
}
void solve(int n)
{
int i, j, k=0;
for (i = 0; i<n; i++)
    for (j = 0; j<n; j++)
        A[i][j] = maze[i][j];

while (1)
{
    for (i = 0; i < n; i++)
    {   
        for (j = 0; j < n; j++)
            if (A[i][j] == k)
            {
                if (0 <= i + 1 < n && 0 <= j < n && A[i + 1][j] == -1)
                    A[i + 1][j] = k + 1;
                if (0 <= i - 1 < n && 0 <= j < n && A[i - 1][j] == -1)
                    A[i - 1][j] = k + 1;
                if (0 <= i < n && 0 <= j + 1 < n && A[i][j + 1] == -1)
                    A[i][j + 1] = k + 1;
                if (0 <= i < n && 0 <= j - 1 < n && A[i][j - 1] == -1)
                    A[i][j - 1] = k + 1;
                if (A[i][j] == -3)
                    break;
            }
    }
    k++;
}
printf("%d\n", k);
printA(VERTICES);
}

main()
{
solve(VERTICES);
}

【问题讨论】:

  • 省略返回值类型是不好的,除非你使用的是太旧的编译器。
  • 尝试谷歌搜索“广度优先搜索 c”。
  • 可能是Lee algorithm?
  • @Tomer 或 Dijkstra?
  • 谢谢大家,但我不能在这里应用 BFS 和 Dijkstra,也找不到 lee 算法..我几乎是 C..T.T 的新手

标签: c shortest-path


【解决方案1】:

我知道,这应该是一个表扬,但我没有足够的声誉.. 无论如何:

您还可以寻找 a*(a-star)算法来解决您的问题,有大量可用的实现和描述,例如:

http://code.activestate.com/recipes/577457-a-star-shortest-path-algorithm/

http://www.codeproject.com/Articles/9880/Very-simple-A-algorithm-implementation

heyes-jones.com/astar.php

【讨论】:

    【解决方案2】:

    正如 Jan Raufelder 建议的那样,您可以使用 A* 算法,它是速度和准确性之间的最佳折衷方案,广泛用于视频游戏。但是,在某些情况下,A* 会在很长一段时间后提供最短路径,而这些最坏的情况大多出现在迷宫中。

    ███████████████████████  In this case,
    ██ S       1 ██ E    ██  A* will start at S,
    ██   █████████████   ██  explore branch 1,
    ██            2 ██   ██  then branch 2,
    ██   █████████████   ██  and then branch 3,
    ██            3 ██   ██  before taking branch 4
    ██   █████████████   ██  to finally get to E.
    ██            4      ██  It still gives you the shortest path,
    ███████████████████████  but it takes a huge time.
    

    如果您想要一个更稳健且通常更快的解决方案,您可以尝试将您的迷宫转换为图形(顶点和边),并在其上应用 Dijkstra 算法。但这意味着你要重做迄今为止所做的所有事情,并花一些时间考虑如何在内存中构建迷宫,因为它不仅仅是int 的二维数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 2021-02-12
      • 2017-08-08
      • 2020-03-19
      相关资源
      最近更新 更多