problem 15 generalized solution for non square grids