Bismillahir Rahmanir Rahim.
Hadith
Rasul Allah (sal Allahu alaihi wa sallam) said: “Allah has forgiven my followers the evil thoughts that occur to their minds, as long as such thoughts are not put into action or uttered.” [Sahih Bukhari]
Commentary: Sometimes evil thoughts come to us the occurring of which we have no control over. When Shaytaan or our nafs puts such thoughts in our minds, and we do not entertain them, then Allah (subhana wa ta’ala) in His Infinite Mercy and Justice does not hold us accountable for them. Not entertaining such thoughts means to not continue to think about them, not speak of them, and not act according to them.
If our mind keeps mulling the thoughts over, or God Forbid takes pleasure in such thoughts, then we will not automatically be forgiven them, for we chose then to think on such lines. In order to stop thinking about something it helps to get up and start doing some physical work.