Dundee threw away a two-goal lead only to win the Scottish Cup quarter-final replay in extra-time thanks to a fine strike by Steven Craig.
After a goalless first half, Bobby Mann headed Dundee in front before Simon Lynch glanced in a second.
But Accies pulled one back when a Juanjo free kick sailed straight into the net and Pat Keogh forced an equaliser over the line.
Craig smashed the winner a minute into extra-time to earn a tie with Gretna.
Accies won a corner inside the first minute and from that, Mark McLaughlin got above Lee Wilkie to head goalwards, but the ball flew just wide.
At the other end, Kelvin Jack had to be alert to block a Mark Gilhaney drive at his front post after 28 minutes.
Dundee finally made the breakthrough 11 minutes into the second half.
A long throw by Paul Dixon was met by the head of Mann 10 yards out and he managed to loop the ball past the outstretched right glove of McEwan.
Bobby Mann celebrates Dundee's opening goal
That lead was almost doubled 10 minutes later when Wilkie flicked the ball towards goal, but this time McEwan got a hand to the ball to push it clear.
But Dundee's second goal was not long in coming. Tam McManus played a short corner and when he got the ball back, he swung in a vicious cross that was glanced into the net by Lynch.
Accies gave themselves a lifeline, though, from another free kick wide on the left.
Juanjo whipped the ball into the area and it was missed by everyone as it flew into the net.
Dixon saw a goal-bound free kick pushed away by McEwan and moments later Hamilton were level.
Another Juanjo free kick was knocked back across goal and as a crowd of players went for the ball, it came off the shoulder of Keogh on its way into the net.
If there was a suspicion of offside about the equaliser, there was certainly a decent shout for handball in the lead-up to Dundee's third goal, which came in the second minute of extra-time.
As Craig chested the ball down, it bounced off his wrist before he sidestepped McLaughlin to fire an unstoppable shot high past McEwan.
Accies had a couple of half-chances to force the tie into a penalty shoot-out, but Dundee held firm to secure a semi-final place.
Dundee: Jack, McCluskey, Mann, Wilkie, Dixon, Robertson, McManus (Ferguson 98), Kevin McDonald, Brady, Deasley (Craig 76), Lynch (Calum McDonald 116).
Subs Not Used: Murray, Law.
Booked: Kevin McDonald, McManus.
Goals: Mann 56, Lynch 68, Craig 91.
Hamilton: McEwan, Balmer, Thomson (Wilson 70), McLaughlin, Ferguson (Juanjo 51), Robertson, McArthur, Neil, Tunbridge (Keogh 70), Wake, Gilhaney.
Subs Not Used: Jellema, Elebert.
Booked: Thomson, Balmer.
Goals: Juanjo 75, Keogh 82.
Ref: D McDonald