A parent is always allowed to claim their child regardless of the living arrangements. However, only one parent can claim the child at a time. The IRS has tie-breaker rules for these situations. 1. Parent with whom the child lived with longer, 2. If time spent with parents is evenly divided it then goes to the parent with the highest Adjusted Gross Income (usually parent with the higher income, but not always).
Now, if neither parent can claim the child, then the person with the highest AGI may claim the child. If two sets of grandparents would like to claim the same child, tie-breaker rule #2 applies.
Another sticky situation is live-in boyfriend/girlfriends. If the parent lives with a partner and is not going to claim their child, they first need to determine whether the non-custodial parent is going/able to claim the child before offering to allow their partner to claim the child. And since that person is not directly related to the child they will be limited as to which credits they are entitled to.
Of course, you can always come to an agree with the other parent to try to avoid these situations.