STILLWATER, Okla. (AP) -- J.W. Walsh had the answer when Oklahoma State needed it the most.
Walsh found Charlie Moore for a 6-yard touchdown pass with 4:13 left in the fourth quarter to help No. 21 Oklahoma State rally for a 33-29 win over Kansas State.
Walsh finished 24-of-38 passing for 245 yards for the Cowboys, who narrowly avoided their second straight loss after a defeat at West Virginia last week.
After falling behind 29-23 in the fourth quarter, Oklahoma State (4-1, 1-1 Big 12 Conference) drove 75 yards in six plays. Walsh was 4-of-5 passing on the drive, including the go-ahead touchdown pass to Moore.
Ben Grogan later added a field goal for the Cowboys, one of four in the game for the freshman.
Daniel Sams accounted for 299 yards of total offense and three touchdowns for the Wildcats (2-3, 0-2). However, the sophomore also threw three interceptions and lost a fumble as Kansas State lost its second straight.
The Cowboys entered the season as the preseason favorite in the Big 12, but their lofty expectations appeared in jeopardy after Kansas State went ahead 29-23 with 6:09 remaining in the fourth quarter.
The Wildcats did so on a 3-yard touchdown run by Sams, who entered the game having only thrown four passes all season while sharing time with Jake Waters at quarterback.
Sams played the majority of the game on Saturday for Kansas State, finishing 15-of-21 passing for 181 yards and a pair of touchdowns. The sophomore also finished with 118 yards rushing on 27 carries, nearly helping the Wildcats overcome 12 penalties for 92 yards.
Oklahoma State led 17-14 at halftime thanks to a 3-yard touchdown run in the second quarter by Walsh, who bounced back from a difficult game in the loss a week ago to the Mountaineers.
The sophomore's best moment, however, came following the Sams' touchdown that put Kansas State up in the fourth quarter.
Following the score, Walsh opened the Cowboys' drive with completions of 12 and 26 yards to Josh Stewart and Tracy Moore, respectively. After a 16-yard run by Jeremy Smith, Walsh added a 15-yard strike to Brandon Sheperd before capping the go-ahead drive with his touchdown pass to Charlie Moore.
Oklahoma State's Shaun Lewis and Daytawion Lowe followed with interceptions to end the Wildcats' final two drives and secure the win.
Sams put Kansas State up 7-0 in the first quarter with a 67-yard touchdown pass to Glenn Gronkowski, a play on which he faked the run before pulling up and slinging the ball over the middle to the streaking fullback.
The sophomore also found Torell Miller for a 17-yard touchdown pass to put the Wildcats up 21-17 to open the third quarter.
Grogan, who missed a pair of field goals in the loss to West Virginia, answered with a pair of field goals following Kansas State turnovers to put the Cowboys back up 23-21. The freshman connected from 30, 34, 23 and 28 yards out.