Monday 15 February 2010

algorithm - Finding number of ways a piece on a chess board can move with number and type of moves given -


This is a dynamic programming problem on which I came to a site. I solved the problem with the algorithm given below. Although the answer I received was correct, evaluation shows that the time limit is high.

The problem is, on the N * N board, one piece is on one place (XP, YP). (Xd, yd) and if only if abs (xd-xp) + abs (yd-yp) & lt; = S. Piece M runs the problem N, S, M and (xp, yp) and I have to figure out how the piece can run M on this board.

My solution was as follows:

  one step from the initial matrix M 00, excluding 1 in the initial position (XP, YP) ​​with all the 0 S For N * N Matrix M1 Create NN matrix M2 for two steps from Matrix M1 ... keep moving M and the sum of the elements of the last matrix MM gives me the way the piece is n * N can be given on the board, it is the obstacle given distance.   

My calculus to calculate the matrix is ​​as follows:

  for each element (E) in matrix M, in S * S Consider the element (s) in the distance given the obstacle in the problem) boxes around the elements. If (stomach (es.xe.x) + es.ye.y) & lt; = S, then m [east] [ii] = m [east] [AI] + M [ESX] [SS .Y]. (The way in which the approach can be reached with e-ways, so that in the matrix the position of E can be included in # such methods can be reached from EE) in the S * S box, I According to my understanding, the above solution (N ^ 2) * (S ^ 2) moves at a slow pace, although it considers the right answer . Please suggest the idea of ​​implementing it in N ^ 2 time as it contains 2D board, I think it can not be done in time (N), but I can be wrong.   

The key to this type of problem is to use partial results using a sliding window is. For example, suppose you know that the sum of 1 to 1000 elements of array X was 1234, and wanted to know the sum of 2 to 1001 elements. The quickest measure is to calculate 1234 + X [1001] -X [1].

In this problem, your obstacle at full price is that you are trying to add all the values ​​in diamond size.

If we now slide the window one step vertically, then we can calculate the new yoga by adding the values ​​to the bottom and taking it away from the top left:

  .. A .. ..- AAA .--a. ... b. ..a .. - & gt; ..a ++ = ..bbb ..... ... + ... b.   

In the diagram we are adding the marked value with +, and removing the marked values ​​together.

It has reduced the number of operations from O (S) ^ 2) to calculate each new value from O (S).

However, you can also do better because you can use the same trick to precompute the sum of values ​​with each diagonal. This lets you calculate each new value in O (1).

No comments:

Post a Comment