这里是从索引[0,0]寻找目标,例如值'9'执行路径查找的代码。 BFS或DFS应该比下面的算法做得更好吗?任何建议更好的算法来完成相同的?二维矩阵中两个位置之间的最短路径
using System;
public class Test
{
public static int[,] matrix =
{
{1, 2, 8, 4},
{3, 0, 3, 4},
{4, 0, 2, 3},
{5, 0, 32, 9}
};
public static int[,] solution = new int[4,4];
public static void Main()
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
FindPath(matrix, 9, rows, cols);
// your code goes here
}
public static void FindPath(int[,] matrix, int destination, int rows, int cols)
{
bool[] visited = new bool[rows * cols];
for(int i=0; i < rows; i++)
{
for(int j =0; j < cols; j++)
{
solution[i,j] = 0;
}
}
for(int i=0; i < rows*cols; i++)
{
visited[i] = false;
}
CountPath(0, 0, visited, rows, cols, 9);
for(int i=0; i < rows; i++)
{
for(int j =0; j < cols; j++)
{
Console.Write(" " + solution[i,j]);
}
Console.WriteLine("");
}
}
public static bool CountPath(int row, int col, bool[] visited, int rows, int cols, int destination)
{
if(row < 0 || row >= rows || col < 0 || col >= cols || visited[row * cols + col] || matrix[row,col] == 0)
{
Console.WriteLine("False...");
return false;
}
Console.WriteLine(matrix[row,col]);
Console.WriteLine(matrix[row,col]);
if(matrix[row,col] == destination)
{
solution[row, col] = matrix[row,col];
Console.Write("Found\n");
return true;
}
visited[row * cols + col] = true;
solution[row, col] = matrix[row,col];
Console.WriteLine(row);
Console.Write(col);
Console.WriteLine("-------------");
bool hasdestination = CountPath(row + 1, col, visited, rows, cols, destination) ||
CountPath(row , col + 1, visited, rows, cols, destination) ||
CountPath(row - 1, col, visited, rows, cols, destination) ||
CountPath(row , col - 1, visited, rows, cols, destination);
if(!hasdestination)
{
Console.WriteLine("No luck go back...");
solution[row, col] = 0;
return false;
}
return true;
}
}
尽管您的代码不会返回路径,但您为什么要搜索值的路径? _pathfinding_是您正在寻找的正确术语吗? – AntiHeadshot
既然你问了另一个算法,我建议你看看A *算法:http://theory.stanford.edu/~amitp/GameProgramming/AStarComparison.html –
改编:图中最短的路径是我在找什么 – sunny