recursive algorithm to detect target