Finding a way in the IOP labyrinth

Introduction and problem statement

We will denote the labyrinth by the abbreviation IOP, if it.

  • Rectangular and described by a size matrix m\times n where in each cell (matrix cells) a sign of patency is encoded.

  • From each passage cell you can go to any adjacent passage cell vertically, horizontally, and along both diagonals, provided that the latter exists.

The cost of moving to an adjacent cell vertically or horizontally is 1. The cost of moving to an adjacent cell along any diagonal is equal to \sqrt2.

We will call moving to an adjacent cell elementary movement.

Delivery of the task. Find the shortest path in a given maze between two passage cells of this maze. When finding a path, only integer variables can be used. Errors in calculations are not allowed. The algorithm should (at least in theory) work with arbitrarily large labyrinths.

Idea of ​​solutions

To find the shortest path, you can use either the Bellman-Ford algorithm or the Dijkstra algorithm. Lee's algorithm (wave algorithm) is not suitable because it assumes that all edges of the graph have the same cost. The Floyd-Warshell algorithm for finding the shortest paths from each to each vertex will also theoretically work, but will require (at least in the worst case) m^2 \times n^2 memory for intermediate calculations and results.

So, as you can already guess, you need to come up with and program some type of data that will store distances.

Both algorithms involve the use of only two number operations.

  • Addition

  • Comparison

Note that the length of any path in such a labyrinth is always the sum of elementary movements along horizontals, verticals and diagonals.

If we sum up only the lengths of elementary movements along horizontals and verticals, we get a number of the form: aWhere a – non-negative integer.

If we sum only the lengths of elementary movements along the diagonals, we get a number of the form: b\sqrt2 Where b – non-negative integer.

Thus, the length of the entire path will be equal to the sum of these two numbers: a+b\sqrt2. In what follows we will call such numbers composite. We will also call the corresponding data type composite number. Obviously, there will only be two values ​​as fields of a composite number a And b.

For composite numbers, it is enough to implement the addition and comparison operations. If this can be done, then the above algorithms will be able to use composite numbers to solve the problem at hand: finding the shortest path.

Let's start analyzing the operations.

Addition

Formulation of the problem. Let there be two numbers: c_1=a_1+b_1\sqrt2 And c_2=a_2+b_2\sqrt2 Where a_1, a_2, b_1, b_2 – some integers. We need to find their sum: c=c_1+c_2.

Solution. We find: c=a_1+b_1\sqrt2+a_2+b_2\sqrt2=(a_1+a_2) + (b_1+b_2)\sqrt2. Thus, to find the sum, it is enough to simply add the corresponding parts of the original numbers.

Comparison

General Information and Helper Property

For both algorithms it is enough to implement more surgery. However, Dijkstra's algorithm for finding the unvisited vertex with the minimum path length can use priority queue instead of linear search. Whatever the type of element of such a queue, you must be able to compare it with another object of the same type. Often, a comparator is used for this, which can show how two objects relate. Such a comparator takes two objects and produces one of the following three values.

  • Less than: The first argument is less than the second (usually coded as -1)

  • Equal: the arguments are equal (usually coded as 0)

  • Greater than: the first argument is greater than the second (usually coded as 1 )

We will consider the comparison of our two numbers “through the prism” of the implementation of such a comparator. In what follows, we will call the operation that such a comparator implements ratio operation and denoted by the symbol \Leftrightarrow.

Let us introduce the unary operation inverting the result relation operations. We show what results from its application in the following table.

Result of the ratio operation

Inverting the result
relation operations

Less

More

Equals

Equals

More

Less

When encoding the result with the above values, the operation of inverting the result of the ratio operation is nothing more than the operation unary minus. Therefore, for brevity, we will call it unary minus and denoted by the sign –.

As part of the task that will be posed below, it will be necessary to solve 4 inequalities(>,<,\leq, \geq)and equation(=). In order to generalize these solutions, we move from solving inequalities and equations to solving ratios. As you might guess, we will relate two objects using the operation \Leftrightarrow.

When solving an inequality, it is often necessary to multiply the inequality by a negative number and change the sign. Let us show that such an analogue for the relation operation is the operation unary minus.

We will use the sign \bullet to generalize all inequalities.

Multiplying an inequality by a negative number can be broken down into two steps. Let some inequality be multiplied by a negative number p . Number p can always be factorized into the following: –p And -1 . Both sides of the inequality can first be multiplied by a positive number –p . And then multiply the inequality by -1 and change the sign to the opposite one. Since this can always be done, in what follows we will only talk about multiplying the inequality by -1.

Let us have some true inequality x\bullet y . Let us perform the following sequence of actions with this inequality. At each step, the newly obtained inequality remains true.

  1. Let's multiply both sides of the inequality by -1 the sign of inequality changes to the opposite.

  2. Let's move the right side of the inequality to the left, and the left side of the inequality to the right.

  3. Let us again multiply both sides of the inequality by -1 and change the sign.

Since when transferring from one part of an inequality to another, the sign of the transferred part changes to the opposite, then as a result of the actions performed, the sign changed twice. The inequality took the form: -y\bullet -x. This fact means that multiplying by a negative number and changing the sign of the inequality is equivalent to multiplying by the same negative number and exchanging the left and right sides of the inequality. Wherein sign change there is no inequality.

Obviously, the ratio operation should also produce same resultif both arguments are multiplied by -1 and they were exchanged. How does the result of a relation operation change if arguments are exchanged? The following statements are obvious.

  • If the result of the operation was morethen he should become less.

  • If the result of the operation was lessthen he should become more.

  • If the result of the operation was equalsthen it should remain unchanged.

Thus, if we return the arguments to their places, but leave them multiplied by -1then the result of the operation must be inverted.
So, it turned out verbose, but an auxiliary property that will be useful later is obtained:-x \Leftrightarrow -y \equiv -(x \Leftrightarrow y ).

Problem statement and solution

Formulation of the problem. Let there be two numbers: c_1=a_1+b_1\sqrt2 And c_2=a_2+b_2\sqrt2Where a_1, a_2, b_1, b_2 – some integers. Correlate c_1 And c_2.

Solution. Our relationship looks like: a_1+b_1\sqrt2 \Leftrightarrow a_2+b_2\sqrt2 .

Let's move everything to the left side and group it: (a_1-a_2)+(b_1-b_2)\sqrt2 \Leftrightarrow 0.
Note that the action performed is nothing more than a subtraction. Let us introduce the following replacements: a=a_1-a_2 , b=b_1-b_2 . We substitute and get: a+b\sqrt2 \Leftrightarrow 0. You can see that the relationship has simplified, so our composite number receives one more operation: subtraction. And we will correlate the difference of the first and second arguments with zero.

So our ratio isa+b\sqrt2 \Leftrightarrow 0. Let's reschedule b\sqrt2 to the right and we get a\Leftrightarrow -b\sqrt2.
Let's multiply the left side of the inequality by |a|and the right one to |b\sqrt2|. This is almost squaring, but at the same time multiplying by a non-negative number. The module can then be expanded by considering 4 cases.

So we have: a|a|  \Leftrightarrow -|b\sqrt2|b\sqrt2.
Let's summarize the cases in a table.

No.

Case description

Inequality

1

a\geq 0, b\geq 0

a^2\Leftrightarrow -2b^2

2

a\geq 0, b < 0

a^2\Leftrightarrow 2b^2

3

a < 0, b\geq 0

-a^2 \Leftrightarrow -2b^2 \rightarrow -(a^2 \Leftrightarrow 2b^2)

4

a < 0, b < 0

-a^2\Leftrightarrow 2b^2

After some understanding of the results obtained, we introduce a function for obtaining the sign of a number: Sgn(v) =\{1, v>0;  0, v=0;-1,v<0\} and sketch out the following algorithm.

  1. s_a:=Sgn(a),s_b:=Sgn(b).

  2. If s_a=0 or s_b=0then we returns_a+s_band complete the algorithm.

  3. If s_a=s_bthen we return s_b and complete the algorithm.

  4. We return s_a \times (a^2 \Leftrightarrow 2b^2).

Let's describe the steps in more detail.

  1. Sign calculation a And b.

  2. Let's consider three cases.

    1. If s_a=0 And s_b=0that means a=0 And b=0, from which it follows that the corresponding numbers are equal. Therefore we return the value s_a+s_b=0.

    2. If s_a\neq 0 And s_b=0That s_a+0=s_a. A number that correlates with zero: a+0\sqrt2=a. If s_a=1That a>0″ src=”https://habrastorage.org/getpro/habr/upload_files/8a7/434/c02/8a7434c02d9f4dc90289e94d7aee9368.svg” width=”46″ height=”16″/>, which means the first argument is greater than the second.  If <img data-lazyloaded= That a<0which means the first argument is less than the second.

    3. If s_a =0 And s_b\neq 0That 0+s_b=s_b. A number that correlates with zero: 0+b\sqrt2=b\sqrt2. If s_b=1That b>0″ src=”https://habrastorage.org/getpro/habr/upload_files/6e7/2e6/cea/6e72e6cea500177f008c12215c83d1f7.svg” width=”44″ height=”17″/>, which means the first argument is greater than the second.  If <img data-lazyloaded= That b<0which means the first argument is less than the second.

  3. At this step we already know for sure that s_a,s_b \in \{-1;1\}. Condition s_a=s_b checks whether numbers have the same signs a And b or not. If yes, then any (since they are the same) of these values ​​will be the result of the ratio.

    1. If s_a=1 And s_b=1which means a>0″ src=”https://habrastorage.org/getpro/habr/upload_files/6d7/c39/4c5/6d7c394c54551883483be7f106271672.svg” width=”46″ height=”16″/> And <img class= And s_b=-1which means a<0 And b<0. That is, the number that correlates with zero is negative. The latter means that the first argument is less than the second.

  4. At this step, we already know for sure that there are two cases left.

    1. If s_a=1 And s_b=-1which means a>0″ src=”https://habrastorage.org/getpro/habr/upload_files/dfc/3a7/35c/dfc3a735cf8bc2ff9d3ae3cd401cb255.svg” width=”46″ height=”16″/> And <img data-lazyloaded=. Then you need to return a^2\Leftrightarrow 2b^2. Multiplying by s_a doesn't change anything since it's multiplying by one.

    2. If s_a=-1 And s_b=1which means a<0 And b>0″ src=”https://habrastorage.org/getpro/habr/upload_files/5ff/967/ef3/5ff967ef3811919d4956e4a7e7b1df76.svg” width=”44″ height=”17″/>.  Then you need to return <img data-lazyloaded=. Multiplying by s_a changes sign to the opposite.

Nuances of machine computing

Addition

Let's move from theory to practice. Since our bit grid is limited, it is necessary to determine the maximum dimension of the labyrinth at which overflows will not occur and, thus, the shortest path search algorithms will continue to work correctly.

So, theoretically, the shortest path of maximum length is the path passing through all the cells of the maze. The length of such a path (i.e. the upper limit):

  • mnif all movements between cells are vertical or horizontal

  • mn\sqrt2if all movements between cells are diagonal.

In the first case a reaches mnin the second – b . Thus, the greatest value that can be taken a And b – This mn. Because a And b signed integers, then the integer type for them must be chosen so that mn\leq 2^{x-1}-1Where x – natural number, the number of bits in the bit grid. Typically, values ​​with a bit grid size of 8, 16, 32, 64, etc. bits are selected.

Comparison

To analyze the comparison operation for overflows, you can follow these steps:

  • Find the maximum absolute value number (result).

  • Square this value and then double it.

  • Look at the resulting value and understand what bit grid is required to maintain correctness.

The problem statement above does not require the use of composite numbers for anything other than finding the shortest path. Nevertheless, I want to solve the problem “beautifully”. Therefore, we will try to make composite numbers more universal and, thus, “tear them away” from labyrinths. The above method is not suitable for this (more precisely, it is not the best). Why is this so? The curious reader is invited to figure it out for himself.

Let's continue. Let's transform the expression a^2\Leftrightarrow 2b^2 step by step as follows.

  • a^2 \Leftrightarrow b^2+b^2

  • a^2-b^2 \Leftrightarrow b^2

In what follows we will only work with the expression a^2-b^2 \Leftrightarrow b^2.

As we can see, first of all we need to calculate a^2 And b^2. The maximum possible value is obtained by squaring the following number: (2^{x-1}-1)-(-2^{x-1})=2^x-1Wherex– size of the bit grid. We build: (2^x-1)^2=2^{2x}-2^{x+1}+1.

The value obtained above is within the range unsigned numbers double size bit grid: 0<2^{2x}-2^{x+1}+1<2^{2x}-1. To range signed numbers double size bit grid value is included only when x=1. This can be easily verified by solving the inequality 2^{2x}-2^{x+1}+1 \leq 2^{2x-1}-1. A bit grid of size 1 for solving the given problem is unlikely to be interesting.

Thus, to calculate the correct values ​​of the expressions a^2 And b^2 It is enough to use a bit grid of twice the size. The value must be unsigned. Example: if a And b are 32-bit signed numbersthen their squares must be stored in 64-bit unsigned numbers.

Next we note that if a^2<b^2That a^2-b^2<0then the result should be less, since any negative number is less than a non-negative one. If a^2 \geq b^2then transfer during subtractions will not occur and it will be possible to correlate a^2-b^2 And b^2no problem.

Comment: the subtraction operation now involves expanding the bit grid. Since this is now a fairly specialized procedure, there is no need to put it in this form in the composite numbers interface. Therefore, our composite number either completely lacks this operation, or it must be implemented separately from comparison.

Final calculation algorithm a^2-b^2 \Leftrightarrow b^2 (used in the 4th point of the main comparison algorithm). Numbers a And b is the result of subtracting related numbers. To store them, an already doubled (relative to the ratio arguments) bit grid is used.

  1. Calculate absolute value a and convert to an unsigned number with a bit grid of the same dimension.

  2. Square the value obtained in the previous step.

  3. Follow the previous steps for the value b.

  4. If a^2<b^2 or a^2-b^2<b^2 then return -1. Otherwise, return 1.

Bonus

For use with mazes and shortest path algorithms, it is convenient to isolate the following elementary values ​​of our composite number: 0, 1, \sqrt2.

Examples of labyrinths and found paths

Example 1

Example 1

Example 2

Example 2

Instead of a conclusion

All the code is here: https://github.com/apodavalov/maze. The comparison algorithm differs slightly from that described in this article.

It's up to you to decide how useful what is described in this article is. The problem is at least definitely solved: it turned out good just for fun.

Articles in a similar style, analyzing various algorithms and data structures, can be found on my Telegram channel (https://telegram.me/GetHiredByFAANG). This article is slightly different from my usual articles on the channel, as it examines a rather specialized algorithm.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *