p(1) = current;
时间: 2024-03-22 16:39:37 浏览: 58
在 MATLAB 中,数组的下标索引从 1 开始,因此 `p(1)` 表示数组 `p` 的第一个元素。
在上面的代码中,`p` 数组的初始值都被赋值为 NaN,因此需要在最后将起点存储在 `p` 数组的第一个元素中,表示起点是最短路径上的第一个节点。
具体实现过程可以参考以下代码:
```matlab
function p = get_path(cameFrom, current)
inds = find_nonempty(cameFrom);
p = nan(1, length(inds));
i = length(inds);
while isKey(cameFrom, current)
p(i) = current;
current = cameFrom(current);
i = i - 1;
end
p(1) = current;
end
```
该函数会首先调用 `find_nonempty` 函数获取非空元素的索引,然后利用 `nan` 函数创建一个初始值为 NaN 的数组 `p`,用于存储最短路径上的节点。
接着,从终点开始倒序遍历每个节点的前驱节点,将它们存储在 `p` 数组中,并返回最短路径。在存储节点时,需要注意数组 `p` 的索引与字典 `cameFrom` 中节点的索引是反向的,因此需要从数组末尾开始存储节点。最后,需要将起点存储在 `p` 数组的第一个元素中,表示起点是最短路径上的第一个节点。
相关问题
function p = get_path(cameFrom, current) % Returns the path. This function is only called once and therefore % does not need to be extraordinarily efficient inds = find(cameFrom); p = nan(1, length(inds)); p(1) = current; next = 1; while any(current == inds) current = cameFrom(current); next = next + 1; p(next) = current; end p(isnan(p)) = []; end
这是一个用于获取路径的函数,输入参数为cameFrom和current。其中cameFrom是一个矩阵,表示每个节点的前驱节点,current是终点节点。该函数通过查找cameFrom矩阵,从终点节点开始一步一步往回找,直到找到起点节点,并返回路径。具体实现过程如下:
1. 找到所有非零元素的位置,即有前驱节点的节点位置。
2. 初始化路径p为NaN向量,长度为非零元素的个数。
3. 将终点节点current赋值给路径p的第一个元素。
4. 初始化next为1,表示当前已经找到了路径的第一个节点。
5. 在current的前驱节点中查找下一个节点,即在cameFrom中查找值为current的元素位置,将其赋值给current,并将其添加到路径p中。
6. 如果current为起点节点,则停止查找,返回路径p。
7. 否则,将next加1,继续查找下一个节点。
8. 最后,删除路径p中的NaN元素并返回路径p。
需要注意的是,由于该函数只会被调用一次,因此并没有特别高的效率要求。
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node *link; }JD; main() {JD *h,*f; int j,x; h=(JD*)malloc(sizeof(JD)); /*生成表头结点*/ h->data=0; f=h; for(j=1;j<=5;j++) /*调用lbcr函数生成具有5个结点的单链表*/ {scanf("%d",&x); f=lbsc(f,x);} for(j=1;j<=5;j++) /*输出生成的单链表*/ {h=h->link;printf("%d,",h->data);} printf("\n"); } lbsc (JD *p,int x) { JD *s; s=(JD*)malloc(sizeof(JD)); s->data=x; p->link=s; return s;} typedef struct node node*insert(node * head, int x) { node * last, * current, * p; //要插入的结点 p = (node *)malloc(sizeof(node)); p->num = x; //空表插入 if(head == NULL) { head = p; p->next = NULL; return head; } //找插入位置 current = head; while(x > current->num && current->next != NULL) { last = current; current = current->next; } if(x <= current->num) { if(head == current)//在第一结点之前插入 { p->next = head; head = p; return head; } else//中间位置插入 { p->next = current; last->next = p; return head; } } }
这段代码包含两个函数,第一个函数是 lbsc,它接受一个 JD 类型的指针 p 和一个 int 类型的数据 x,返回一个 JD 类型的指针。函数的作用是生成一个单链表,并将 x 插入到链表的最后一个节点后面。第二个函数是 insert,它接受一个 node 类型的指针 head 和一个 int 类型的数据 x,返回一个 node 类型的指针。函数的作用是将 x 插入到一个已排序的链表中,使得链表仍然保持有序。如果链表为空,则将 x 插入到链表的头部;如果链表不为空,则找到 x 在链表中的位置,并将其插入到该位置之前或之后。
阅读全文
相关推荐












