@Alireza: For 9 there is definitely a neat formula. I would recommend either investigating this with grids of different dimensions and/or thinking about the ways the line passes from one square to another. 21 was not easy - there’s been some discussion already in these comments (including from me)
on /blog/120