I don't know if you have different coding for the player and for NPCs, but a potential fix would be walls that are invisible and intangible to the player but solid to NPCs. You can create boxes around NPCs to prevent them from moving outside of certain areas, and also make clear spaces around doors and hallways.