What is the difference between these two Edit Distance Algorithm
I'm going to assume by &quot;doesn't work&quot; you mean &quot;gives the wrong answer&quot;.
In dynamic programming, every cell in the table is supposed to represent a solution to a subproblem. In the case of edit distance, the subproblem is

Let dp[i][j] be the distance between word1.substring(i) and word2.substring(j)

But in your code, the statement of the subproblem is ambiguous. The cell dp[i][j] contains something that depends on count, but which count? It might very well be that many different counts correspond to the same pair i,j, because you can get to it by different &quot;routes&quot;. If that happens, your program will just use whatever count it encountered first, write the answer to the table and never revise it again. Therefore, if the first route you took is not the optimal one, then the result will be wrong.
Consider what happens when I give your program the words &quot;WORD&quot; and &quot;SWORD&quot;. Which number will be in dp[3][4]? The correct program will write 0 into that cell, and eventually it will find a route that leads to the point 3,4 and has a cost of 1. Your program, on the other hand, will write the count of the first route it takes, which in this case will be  4. And even though it may later find a better route, it will still trust that 4, because that's what the table says.
In summary, you make a subproblem with the indices i,j depend on some other quantity, which violates the principles of dynamic programming. If your dp table had a third dimension, as in dp[i][j][count], then it might have worked, because then every subproblem would be fully specified.