Robert Lewandowski saved his team from a humiliating German Cup exit as Bayern Munich came from behind to beat second-tier Heidenheim in a 5-4 thriller on Wednesday.

Bayern were 2-1 down at half-time having gone down to ten men early in the game, and threw away a two-goal lead in the second half.

Yet Lewandowski’s late winner ended a rollercoaster resistance from Heidenheim and sent Bayern into the semi-finals.

Everything seemed to be going according to script when Bayern took the lead from a corner on 12 minutes. Leon Goretzka was left unmarked to head the ball in from point blank range.

Yet the script went up in flames when Bayern went down to ten men just minutes later.

Niklas Suele was initially booked for a challenge on Robert Andrich, but a video review convinced the referee that Suele had denied Andrich a goalscoring opportunity.

The red card galvanised Heidenheim and they forced several chances before Robert Glatzel headed in the equaliser just before the half-hour mark.

Ten minutes later, the Allianz Arena was silenced as Marc Schnatterer fired Heidenheim in front.

Thomas Mueller brought Bayern level after half-time, turning in Lewandowski’s header with a marvellous, swivelling finish.

He then returned the favour three minutes later, setting up Lewandowski to restore the lead for Bayern.

Serge Gnabry added a fourth for Bayern on 65 minutes, slotting the ball in at the far post at a corner.

Yet Glatzel stunned Bayern again when he scored twice in three minutes to make it 4-4.

Having pulled a goal back on 74 minutes, the Heidenheim striker completed his hat-trick from the penalty spot.

It ended in disappointment for Heidenheim, however, as a handball at the other end allowed Lewandowski to score the winner with an 84th minute penalty.