无法输入图形
Unable to Input the graph
我在c++中解决问题http://www.spoj.com/problems/SHOP/,但我无法弄清楚如何输入图形以进一步应用Dijkstra算法。下面是图表格式——
4 3
3
4 2 X 4
第一行表示&
"S" &"D"-分别表示源和目的
数字-表示通过该块所需的时间,"X"-表示禁止进入区域。
如何根据DIjkstra算法的要求转换下面的图中的节点和边。我不知道怎样把地图转换成图表。
不需要转换。想象你在某个点(i,j)(我假设每个方格允许你走四步)。然后,你可以去(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)如果:
1)该索引在表内2)该索引未标记X
你给了平方S的位置你的Dijkstra算法。每次你向你的数据结构中加入新的允许平方集。一旦你到达D的位置,你打印它。
此外,这个问题对我来说似乎并不重要,所以你可以使用一个简单的BFS,也可以使用一个队列。但是如果你想用Dijkstra算法去不同的方格会有不同的代价。如果您使用优先队列而不是队列。例如,您可以使用如下的数据结构集:
int dist[][]; // this contains the cost to get to some square
//dist is initialized with a large number
struct node{
int i, j; //location
node(int ii, int jj){
i = ii;
j = jj;
}
bool operator < (node &n)const{ //set in c++ will use this to sort
if(dist[i][j] == dist[n.i][n.j]) return i < n.i || j < n.j; //this is necessary
return dist[i][j] < dist[n.i][n.j];
}
};
set <node> q;
int main(){
//initialized dist with large number
dist[S.i][S.j] = 0; //we start from source
q.push(node(S.i, S.j));
while(true){
//pick the first element in set
//this element has the smallest cost
//update dist using this node if necessary
//for every node that you update remove from q and add it again
//this way the location of that node will be updated in q
//if you see square 'D' you are done and you can print dist[D.i][D.j]
}
return 0;
}
不需要将矩阵转换为节点和边。您可以创建包含(行号,列号,时间)的结构,其中时间将表示从源到达此坐标所花费的时间。现在以key为时间,创建这个结构的最小堆。现在从最小堆中提取元素(最初源将在最小堆中,时间为0),并将相邻元素推入最小堆(只有那些未访问且不包含X的元素)。继续这样做,直到提取的元素不是目标。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 如何接受来自输入文件的图形
- 从输入文件打印图形
- 根据用户输入创建使用C 的图形
- 基于文件的输入来定义图形变量
- 使用图形时输入
- 使用Opencv从鼠标进行图形输入
- 如果图形以邻接表的形式给出,如何扫描用户输入
- 无法输入图形