安卓开发来体验一下A*算法寻路...

144 阅读2分钟

前言

近期由于涉及到导航相关的内容,需要涉及到最短寻址,就浅浅的研究了一下相关的算法,比较出名的就是A*算法和D算法,本篇文章我就自己写的一个demo的例子,来分享一下个人对这个算法的实践。

什么是A*算法

A* (A-Star)算法是一种静态路网中求解最短路径最有效的直接搜索方法,也是解决许多搜索问题的有效算法。 上面当然是百度百科的解释,但我个人理解而言,就是一种寻找最短路径的算法,但效率上不是最快的。

image.png 图示是一个8*8的区域,左侧是起点,右侧是终点,中间的障碍物。我们怎么样来走出一条从起点到终点的最短的路径呢?A-star算法的思路是这样:维护两个列表,存储两个list:OpenList/CloseList,这两个类别分别维护即将要去尝试的位置及已经尝试过的位置。并且使用F值来表示最有效的值(F表示类似于权重的东西,越大表示这条路不值得走,越小表示越值得走,F=G+H)。只需要一开始将起点放入OpenList中,直到终点也在OpenList中时,说明最短的路径已经找到了。此时,只需要反向从终点往前寻址即可找到这条路径。([参考文章](https://blog.csdn.net/weixin_44489823/article/details/89382502)) ## 实践 作为一名安卓开发,当然是想使用安卓相关的方式来试试了。很轻易的,我们就可以想到使用自定义view来绘制界面,然后跑一把。由于都比较简单,加上注释很齐全,我这里就直接贴代码了。
package com.mio.testhndemo.ui.view;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.mio.testhndemo.R;

public class GridItemView extends FrameLayout {
    private TextView topLeftTextView;
    private TextView bottomLeftTextView;
    private TextView bottomRightTextView;
    private ConstraintLayout clRoot;

    public GridItemView(Context context) {
        this(context, null);
    }

    public GridItemView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GridItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.grid_item_layout, this, true);
        topLeftTextView = view.findViewById(R.id.top_left_text);
        bottomLeftTextView = view.findViewById(R.id.bottom_left_text);
        bottomRightTextView = view.findViewById(R.id.bottom_right_text);
        clRoot = view.findViewById(R.id.cl_root);
    }

    @Override
    public void setBackgroundColor(int color) {
        clRoot.setBackgroundColor(color);
    }

    public void setTopLeftText(String text) {
        topLeftTextView.setText(text);
    }

    public void setBottomLeftText(String text) {
        bottomLeftTextView.setText(text);
    }

    public void setBottomRightText(String text) {
        bottomRightTextView.setText(text);
    }
}

自定义viewgroup:

效果

image.png

image.png

image.png

缺陷

代码中没考虑没路的情况,如果走不到就没了...后续优化吧...