In the general case, there are a couple of types of positions on the board : Positions from which a knight attacks two squares on the board, those from which it attacks three squares, and so on. So we just need to count the number of squares from which a knight would attack exactly X squares, and add 2 * N * M * (N * M-X-1) to the answer. We multiply by 2 because the knights are distinct. Cases with n = 1,2 and 3 might have to be handled seperately depending on how you prefer to think of the problem. Finally note that the answer for the larger test cases do not fit in a 64 bit integer, and hence simple big integer operations are needed.