Skip to main content
2 of 5
edited tags
mjolka
  • 16.3k
  • 2
  • 30
  • 73

Word ladder solution in Java using matrix

Following is my implementation of Word Ladder problem, can anybody review the code to compare its efficiency with other solutions. Thank you

package arrays;

import java.util.Hashtable;
import java.util.Set;

public class WordLadder {

public static void main(String[] args) throws Exception {
    wordLadder();
}

private static void wordLadder() throws Exception {
    String source = "hit";
    String destination = "cog";
    Hashtable<Integer, String> dict = new Hashtable<Integer, String>();
    dict.put(1, source);
    dict.put(2, "hot");
    dict.put(3, "dot");
    dict.put(4, "dog");
    dict.put(5, "lot");
    dict.put(6, "log");
    dict.put(7, destination);
    formHammingDistanceMat(dict);
}

private static void formHammingDistanceMat(
        Hashtable<Integer, String> dict) throws Exception {
    int mat[][] = new int[dict.size()][dict.size()];
    for (int[] row : mat) {
        java.util.Arrays.fill(row, 99999);
    }

    Set<Integer> keySet = dict.keySet();
    for (int i = 0; i < keySet.size() - 1; i++) {
        String mainString = dict.get(i + 1);
        for (int j = i + 2; j <= dict.size(); j++) {
            if (j == 7)
                System.out.println();
            mat[i][j - 1] = findHamming(mainString, dict.get(j));
        }
    }
    System.out.println(findShortestPath(mat, 0, 1,dict));
}

private static int findShortestPath(int[][] mat, int row, int col,
        Hashtable<Integer, String> dict) {
    if (col == dict.size()-1) {
        return 0;
    }
    if (mat[row + 1][col + 1] == 1) {
        return 1 + findShortestPath(mat, row + 1, col + 1, dict);
    } else if (mat[row][col + 1] == 1) {
        return 1 + findShortestPath(mat, row, col + 1, dict);
    } else
        return 1 + findShortestPath(mat, row + 1, col, dict);
}

private static int findHamming(String mainString, String str)
        throws Exception {
    if(mainString.length()!=str.length()) throw new Exception();
    int count = 0;
    for (int i = 0; i < mainString.length(); i++) {
        if (mainString.charAt(i) != str.charAt(i))
            count++;
    }
    return count;
}
}
amz
  • 33
  • 3