The algorithm imagines that the operating system selects one process and run it to completion. It selects one that it can finish. After finishing process A, it takes back resources that are allocated to A and tries to find another process to run to completion. This continues until either all processes are finished or it is not possible to complete any of the remaining processes.

A basic phase is to select a process that can be finished, then to imagine taking away that process's resources.

Note that the operating system is not required to run processes one at a time. You just imagine doing that in order to see whether it is possible to complete all of the processes.

The algorithms for deadlock detection and for recognizing a safe state differ in assumptions that are made. For deadlock detection, the algorithm assumes that no process requests any resources that it has not already requested. For recognizing a safe state, the algorithm assumes that each process will request all of the resource up to its maximum allowed resources. So one looks at the best case while the other looks at the worst case.