Why are these sheep crowding into this group?

The way of pathfinding in Minecraft works: whenever the AI decides to perform a random walk, a full opaque solid block is selected randomly within a cube centered on the mob feet: up to 7 blocks up or down and 10 blocks away in x, z directions. Then the mob moves towards that block, and stops either upon reaching it, or getting stuck somewhere along the way. source

Your farm is dug into the ground, meaning there's lots and lots of dirt just past the walls - therefore random walking attempts towards the wall will be attempted frequently; the blocks under ground of the farm floor don't create a directional bias so only some sheep wander back towards the center of the paddock; most that pathfind towards the wall just stay there.


This is a very well-known quirk of Minecraft's pathfinding when it comes to mobs and animals, and unfortunately there is not much you can do to stop it, as it is fundamentally built into how the game's creatures move around.

According to this Quora post:

Averaged over a very long period of time, any non-random glitch in a random movement algorithm will produce non-random movement. If that movement is directional, it will push them into a particular corner.

Thinking about this a different way, imagine that you have a pathfinding algorithm for a creature where it tries to move randomly either up, down, left, or right. Each of these movements will therefore have a 25% chance to occur. If there is a corner blocking it from going up or right, however, then the creature will still attempt random movements as normal - 25% up, 25% right, 25% down, and 25% left. However, because it cannot move up or right, 50% of its movement will just keep it squished up in the corner, making it difficult for the creature to escape unless it happens to get a series of lucky "down" or "left" commands.