Рина Сергеева
Рина СергееваJune 12, 2018, 2:34 a.m.

Implementation of the Wave algorithm (Lee algorithm) in Java

Sometimes there is a problem to find the minimum path from point A to point B . The map can have barriers and be like a labyrinth. Similar tasks can be done in game development, PCB design and GPS development, etc.

There is a large set of algorithms for finding the minimum path. The most simple and effective is the Wave trace Algorithm (Lee algorithm). Which is based on the methods of breadth-first search.

This algorithm is not difficult to understand. It will be understandable even for a beginner in programming.


I will give an example of my work. I have a similarity of a cellular automaton (a graph consisting of nodes and edges between them).  It will implement the Lee Algorithm.

The implementation of the algorithm consists of 3 stages:

  1. The initialization of the initial data;
  2. Wave propagation;
  3. Path recovery.

The first step - Initialize the initial data

You need to have an array of objects (nodes, cells). I have this class Node .

Each object has a field of near type, for example, ArrayList.  In this field you write down all the "neighbors" ( neighboring nodes of this node ).

Each node has a check mark available / unavailable.

Start and finish nodes are recorded.

The second stage - Wave propagation

You must have a numeric array (by the number of cells) where the numbers (marks) for each cell will be written. By default, all cell values are zero.

The start node is set to 1.

Check all the "neighboring" nodes of this node for "availability", and check whether they already have a mark.

If everything is suitable, put a mark on 1 more than the previous node. Then check its "neighboring nodes".

Continue until you reach the finish cell.

Code example:
public int[] WavePropagation(int fromNode, int toNode, ElementManager elementManager) {  
        int[] markedNode = new int[elementManager.GetNumberOfAllNodes()]; // array where each node's marks will be located
        int markNumber = 1;                        // counter
        markedNode[fromNode] = markNumber;         // initializing the start node
        while (markedNode[toNode] == 0) {          // until you reach the finish node
            for (int i = 0; i < markedNode.length; i++) { 
                if (markedNode[i] == markNumber) {                                          // we start with the starting node
                    for (int j = 0; j < elementManager.GetNode(i).near.size(); j++) {       // looking all the neighboring nodes
                        if(markedNode[elementManager.GetNode(i).near.get(j).number] == 0    // if it has not yet received a mark
                           && elementManager.GetNode(i).near.get(j).isEnable){              // if available
                            markedNode[elementManager.GetNode(i).near.get(j).number] = (markNumber + 1);
                        }
                    }
                }
            }
            markNumber++;
        }
        return markedNode;
    }

The third stage - Path recovery

In the path array, place the finish node.

View the marks of all nodes that are "neighboring" to the final node. Put in the path array that node, the mark of which is 1 less than the finish node.

Repeat this action until the start node is reached.

Code example:
public ArrayList<Integer> PathRecovery(int fromNode, int toNode, int[] markedNode, ElementManager elementManager) {  
        ArrayList<Integer> paramsPaveTheRoute = new ArrayList<>();       // array where the path is stored
        if (markedNode[elementManager.GetNode(toNode).number] != 0) {    // once again, check whether the algorithm has reached the finish node
            paramsPaveTheRoute.add(toNode);                              // add the finish node to the path
            ElementManager.Node currentNode = elementManager.GetNode(toNode);
            while (currentNode.number != fromNode) {                     // until we reached the starting node
                for (int i = 0; i < currentNode.near.size(); i++) {      // check the neighboring nodes
                    if (markedNode[elementManager.GetNode(currentNode.near.get(i).number).number]
                            == markedNode[currentNode.number] - 1) {     // if the node's markup value is 1 less than the previous node
                        currentNode = elementManager.GetNode(currentNode.near.get(i).number); //node becomes the current
                        paramsPaveTheRoute.add(currentNode.number);      // entered into array
                    }
                }
            }
        }
        return paramsPaveTheRoute;
    }

The result of the program:

So, I think you've seen that the Wave Trace Algorithm (Lee Algorithm) is not at all difficult to implement. It searches for the minimum path by doing a small number of calculations.  If you want, this universal algorithm can be complicated.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks