directory

Use of breadth-first search

Breadth-first search thinking

Sample analysis

code

conclusion


Use of breadth-first search

Breadth-first search and depth-first search are similar in their types of problems, such as maze problems, number list problems, and state search problems. However, the difference between it and depth-first search is that depth-first search is applicable to a wider range, because there are limitations of depth-first search, some topics applicable to depth-first search algorithm may appear the “infinite depth” problem, which will lead to the terrible infinite cycle. However, this does not mean that the depth-first search algorithm is worse than the breadth, because the breadth first search requires the state of all points to be stored in the applicable queue, which will consume more space than the depth. When the topic data is relatively large, it is easy to overmemory. Depth-first search is more suitable for larger data sizes, but it all depends on the specific situation. There is also a problem with breadth-first search called state compression, which I will cover in a separate blog post since it is also a more difficult idea to understand.

Breadth-first search thinking

Those of you who are familiar with depth-first search should know that the implementation of depth-first search is usually stack, recursive, or priority queue, while the implementation of breadth-first search is usually plain queue, and the idea is easier to understand.

Its real idea is from the start, the starting point around the points on the direction in the queue, is removed from the queue head a point, then the points on the direction of the store in the queue, repeated access operation, until meet the qualified point is out of function, or have not been eligible points, until the queue is empty, the exit function. As with depth-first search, you must first determine the orientation problem. For example, in the maze problem, you need to represent four or eight directions with a two-dimensional 4*2 or 8*2 array, and you need to use arrays or other means to mark points that have been traversed.

Sample analysis

Now I’m going to use a simple problem to explain, to strengthen understanding

 

Knight Moves

Problem Description

 

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.

Of course you know that it is vice versa. So you offer him to write a program that solves the “difficult” part. 

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.

Input

The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.

Output

For each test case, print one line saying “To get from xx to yy takes n knight moves.”. 

Sample Input

e2 e4

a1 b2

b2 c3

a1 h8

a1 h7

h8 a1

b1 c3

f6 f6

Sample Output

To get from e2 to e4 takes 2 knight moves.

To get from a1 to b2 takes 4 knight moves.

To get from b2 to c3 takes 2 knight moves.

To get from a1 to h8 takes 6 knight moves.

To get from a1 to h7 takes 5 knight moves.

To get from h8 to a1 takes 6 knight moves.

To get from b1 to c3 takes 1 knight moves.

To get from f6 to f6 takes 0 knight moves.

 

Given an 8 by 8 array, the number of rows is “a-h” and the number of columns is “1-8”, and then given a starting point and an ending point, calculate the shortest number of steps from the starting point to the ending point. It should be noted that the way to move is the horse in type chess, following the character “day”, for example

1  0

0  0

0  1

The way the 1 moves to the 1

code

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

int row_x1, row_x2;// Record the number of lines starting and ending
int col_y1, col_y2;// Record the number of columns at the start and end
char char_x1, char_x2;// Record the number of lines starting and ending, represented by letters
int step;	// Count the steps
bool mark[10] [10];	// Used to record whether the point was traversed
int dir[8] [2] = {{2 -.1}, {2 -.- 1}, {- 1.2 -}, {1.2 -}, {2.- 1}, {2.1}, {1.2}, {- 1.2}};/ / direction

struct Node{
	int x, y, step;
};

queue<Node> Q;

void BFS(a)
{
	Node now, next;

	while(! Q.empty())	// Every time a function is called, the queue is emptied
		Q.pop(a); now.x = row_x1; now.y = col_y1; now.step =0;
	Q.push(now);	// press into the node

	while(! Q.empty()) {
		now = Q.front(a); Q.pop(a);for (int i = 0; i < 8; i++) {
			next.x = now.x + dir[i][0];
			next.y = now.y + dir[i][1];

			if (next.x < 0 || next.x >= 8 || next.y < 0		// Determine if the requirements are met
				|| next.y >= 8 || mark[next.x][next.y])
				continue;

			mark[next.x][next.y] = true;	// The flag has been traversed
			next.step = now.step + 1;	// Add one to the previous step
			Q.push(next);	// Press into the queue

			if (next.x == row_x2 && next.y == col_y2) {		// Exit the function
				cout << "To get from " << char_x1 << col_y1 + 1
					<< " to " << char_x2 << col_y2 + 1 << " takes "
					<< next.step << " knight moves." << endl;
				return; }}}}int main(void)
{
	ios::sync_with_stdio(false);

	while (cin >> char_x1 >> col_y1 >> char_x2 >> col_y2) {
		row_x1 = char_x1 - 'a'; col_y1 -= 1;	// Convert an alphabetic representation to a numeric representation
		row_x2 = char_x2 - 'a'; col_y2 -= 1;

		if (row_x1 == row_x2 && col_y1 == col_y2) {
			cout << "To get from " << char_x1 << col_y1 + 1
				<< " to " << char_x2 << col_y2 + 1 << " takes 0 knight moves." << endl;
		}
		else {
			// It is worth noting here that the two-dimensional array is reset in the same way as the one-dimensional array, using the memset function
			memset(mark, false.sizeof(mark));	// The tag array is reset each time
			BFS();
		}
	}

	return 0;
}
Copy the code

conclusion

Breadth-first search is the basis of ACM, and is also widely used in daily training and competitions, so we need to master it well. In the process of learning, I believe you will gain not only algorithms, but also ideas.