Third edition of Artificial Intelligence: foundations of computational agents, Cambridge University Press, 2023 is now available (including the full text).
3.7.1 Cycle Checking
It is possible for a graph representing a search space to include cycles. For example, in the robot delivery domain of Figure 3.6, the robot can go back and forth between nodes o103 and o109. Some of the aforementioned search methods can get trapped in cycles, continuously repeating the cycle and never finding an answer even in finite graphs. The other methods can loop though cycles, but eventually they still find a solution.
The simplest method of pruning the search tree, while guaranteeing that a solution will be found in a finite graph, is to ensure that the algorithm does not consider neighbors that are already on the path from the start. A cycle check or loop check checks for paths where the last node already appears on the path from the start node to that node. With a cycle check, only the paths 〈s0,...,sk,s〉, where s∉{s0,...,sk}, are added to the frontier at line 16 of Figure 3.4. Alternatively, the check can be made after a node is selected; paths with a cycle can be thrown away.
The computational complexity of a cycle check depends on the search method being used. For depth-first methods, where the graph is explicitly stored, the overhead can be as low as a constant factor; a bit can be added to each node in the graph that is assigned a value of 1 when the node is expanded, and assigned a value of 0 on backtracking. A search algorithm can avoid cycles by never expanding a node with its bit set to 1. This approach works because depth-first search maintains a single current path. The elements on the frontier are alternative branches from this path. Even if the graph is generated dynamically, as long as an efficient indexing structure is used for the nodes on the current path, a cycle check can be done efficiently.
For the search strategies that maintain multiple paths - namely, all of those with exponential space in Figure 3.9 - a cycle check takes time linear in the length of the path being searched. These algorithms cannot do better than searching up the partial path being considered, checking to ensure they do not add a node that already appears in the path.