Convert grid to for loops