Ecological and Social Dynamics of Territoriality and Hierarchy Formation