improoved algorithm, closing door