changed grid.length - 1 to merged_result.length -1 in the down conditional on line 195