Android 图的最短路径算法

序言

为了研究单源最短路径的相关算法,写了一个demo
算法的细节请参考
图的四种最短路径算法

我实现了其中的两种。
在这里插入图片描述
我将算法进行了封装,这是基类

package com.example.mappath;

import androidx.annotation.NonNull;

import java.util.Stack;

/**
 * @author zhuguohui
 * @description:对图的单源最短路径算法的抽象
 * @date :2021/5/12 14:34
 */
public abstract class MapPathAlgorithm {
    protected final int[][] ege;
    /**
     * max表示无法到达
     */
    public static final int max = 999999999;
    MapPathAlgorithm(int[][] ege) {

        this.ege = ege;
    }

    public abstract PathStack getMinPath(int from, int to);

    public static class Edge {
        int from;
        int to;
        int length;

        public Edge(int from, int to, int length) {
            this.from = from;
            this.to = to;
            this.length = length;
        }

        @Override
        public String toString() {
            return (from + 1) + "---->";
        }
    }

    public static class PathStack extends Stack<Edge> {

        private int getPathSize() {
            int size = 0;
            for (Edge edge : this) {
                size += edge.length;
            }
            return size;
        }

        @NonNull
        @Override
        public synchronized String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("路径长度(" + getPathSize() + "):");
            for (int i = 0; i < size(); i++) {
                Edge edge = get(i);
                builder.append(edge);
                if (i == size() - 1) {
                    builder.append(edge.to + 1);
                }

            }
            return builder.toString();
        }
    }

} 

直接使用,相比之前的算法。我的算法可以获取到形成的路径。

  private void start() {
        MapPathAlgorithm apa = rb_dj.isChecked() ? new DijkstraAlgorithm(ege) : new DFSAlgorithm(ege);
        int from = 0;
        int to = 0;
        try {
            from = Integer.parseInt(et_from.getText().toString());
            to = Integer.parseInt(et_to.getText().toString());
        } catch (Exception e) {
            Toast.makeText(this, "请输入正确的数字", Toast.LENGTH_SHORT).show();
            return;
        }
        MapPathAlgorithm.PathStack pathStack = apa.getMinPath(from, to);
//        Log.i("zzz", "找到的路径为:" + pathStack);
        tv_result.setText("找到路径:" + pathStack);
    }

边是通过数组定义的


    private final int[][] ege = new int[][]{
            {max, 2, max, max, 10},
            {max, max, 3, max, 7},
            {4, max, max, 4, max},
            {max, max, max, max, 5},
            {max, max, 3, max, max}
    };

源码

MapPath

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值