Dijkstra算法详细(单源最短路径算法),java面试的基本问题

/* 将当前队列中的所有节点向四周扩散一步 */

for (int i = 0; i < sz; i++) {

Node cur = q.poll();

printf(“从 %s 到 %s 的最短距离是 %s”, start, cur, step);

/* 将 cur 的相邻节点加入队列 */

for (Node x : cur.adj()) {

if (x not in visited) {

q.offer(x);

visited.add(x);

}

}

}

step++;

}

}

这是对于无权图的应用,那么对于有权图我们就不能这么用了,因为有权图的最短路径问题不是依照步数来判断的了。所以我们要进一步简化框架,把while 循环里面的的for 去掉。

// 输入一棵二叉树的根节点,遍历这棵二叉树所有节点

void levelTraverse(TreeNode root) {

if (root == null) return 0;

Queue q = new LinkedList<>();

q.offer(root);

// 遍历二叉树的每一个节点

while (!q.isEmpty()) {

TreeNode cur = q.poll();

printf(“我不知道节点 %s 在第几层”, cur);

// 将子节点放入队列

if (cur.left != null) {

q.offer(cur.left);

}

if (cur.right != null) {

q.offer(cur.right);

}

}

}

如果你想同时维护 depth 变量,让每个节点 cur 知道自己在第几层,可以想其他办法,比如新建一个 State 类,记录每个节点所在的层数:

class State {

// 记录 node 节点的深度

int depth;

TreeNode node;

State(TreeNode node, int depth) {

this.depth = depth;

this.node = node;

}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值