Algorithm to Assign Values Based on Constraints
The problem you are describing amounts to constraint programming and the specific constraint you are talking about is the alldifferent constraint. I'm not offering a purely algorithmic solution, but reading a bit on constraint programming could give you some ideas on how to construct a search tree where you make a decision (i.e., assign a value to a variable) at each node, and how to backtrack to a feasible node when you reach an infeasible node.