在您获得的最终网格上进行深度优先搜索 (dfs)。
http://en.wikipedia.org/wiki/Depth-first_search
您将获得单独的路径。如果你想选择最短的,你可以做的优化很少。
- 保持最大限制,如果 dfs 看起来比这更远,请跳过该路径。
- 如果您找到长度小于最大限制的路径。将最大限制设置为。
希望这会有所帮助。
编辑:我写了这段代码,它应该适合你。它将以向量< pair > 作为 x,y 坐标给出最短路径。
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
ifstream fin("map.txt");
int width, height;
int map[10][10];
// Start (x,y), End (x,y)
int sy, sx, ey, ex;
bool visited[10][10];
vector<pair<int, int> > final_path;
int max_size = 9999;
void getInput() {
fin >> width >> height;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int x;
fin >> x;
map[i][j] = x;
if(x == 8){
sy = i;
sx = j;
}
if(x == 9){
ey = i;
ex = j;
}
}
}
}
void dfs(int x, int y, vector<pair<int, int> > path) {
if(path.size() > max_size){
cout << "Returning : path size too big" << endl;
return;
}
if(x < 0 || x >= width || y < 0 || y >= height){
cout << "Returning : bounds" << endl;
return;
}
// If the tile is blocked, can't go there
if(map[y][x] == 0){
cout << "Returning : blocked" << endl;
return;
}
if(visited[y][x]){
cout << "Returning : visited" << endl;
return;
}
// We don't want to revisit a tile
visited[y][x] = true;
cout << "Visiting " << x << " " << y << endl;
path.push_back(make_pair(x, y));
if(map[y][x] == 9) {
final_path = path;
visited[y][x] = false;
return;
}
dfs(x, y - 1, path);
dfs(x + 1, y, path);
dfs(x, y + 1, path);
dfs(x - 1, y, path);
visited[y][x] = false;
return;
}
int main() {
getInput();
cout << "Got Input" << endl;
cout << width << " " << height << endl;
memset(visited, 0, sizeof(visited));
vector<pair<int, int> > starting_path;
cout << sx << " " << sy << endl;
dfs(sx, sy, starting_path);
cout << "Path size is " << final_path.size() << endl;
for(int i = 0; i < final_path.size(); i++){
cout << final_path[i].first << " " << final_path[i].second << endl;
}
return 0;
}
map.txt 包含您在问题中提供的地图。