One of the most disastrous forms of collective human behaviour is the kind of crowd stampede induced by panic, often leading to fatalities as people are crushed or trampled. Sometimes this behaviour is triggered in life-threatening situations such as fires in crowded buildings; at other times, stampedes can arise during the rush for seats or seemingly without cause. Although engineers are finding ways to alleviate the scale of such disasters, their frequency seems to be increasing with the number and size of mass events. But systematic studies of panic behaviour and quantitative theories capable of predicting such crowd dynamics are rare. Here we use a model of pedestrian behaviour to investigate the mechanisms of (and preconditions for) panic and jamming by uncoordinated motion in crowds. Our simulations suggest practical ways to prevent dangerous crowd pressures. Moreover, we find an optimal strategy for escape from a smoke-filled room, involving a mixture of individualistic behaviour and collective 'herding' instinct.