Skip to content

Instantly share code, notes, and snippets.

@agrawal-priyank
Last active October 29, 2017 04:20
Show Gist options
  • Save agrawal-priyank/48ace8b78e5a609eee34da78c572ef96 to your computer and use it in GitHub Desktop.
Save agrawal-priyank/48ace8b78e5a609eee34da78c572ef96 to your computer and use it in GitHub Desktop.
Search path of a word in a matrix
public class WordPath{
class Coordinate{
public int x;
public int y;
public Coordinate(int x, int y){
this.x = x;
this.y = y;
}
}
char[][] matrix = {{'a', 'b', 'c', 'd', 'e'},
{'f', 'g', 'h', 'i'},
{'j', 'k', 'l', 'm', 'n'},
{'o', 'p', 'q', 'r', 's'},
{'t', 'u', 'v', 'w'},
{'x', 'y', 'z'}};
public static void main(String[] args){
String word = "google";
WordPath wP = new WordPath();
String path = wP.searchPath(word.toLowerCase());
System.out.println(path);
}
public String searchPath(String word){
if(word == null || word.length() == 0){
return null;
}
HashMap<Character, Coordinate> map = new HashMap<Character, Coordinate>();
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[i].length; j++){
map.put(matrix[i][j], new Coordinate(i, j));
}
}
StringBuilder path = new StringBuilder();
Coordinate previous = null, current = null;
String p;
for(int i = 0; i < word.length(); i++){
current = map.get(word.charAt(i));
if(previous == null){
p = getDirection(new Coordinate(0, 0), current);
path.append(p);
previous = current;
} else{
p = getDirection(previous, current);
path.append(p);
previous = current;
}
}
return path.toString();
}
private String getDirection(Coordinate prev, Coordinate curr){
StringBuilder path = new StringBuilder();
int xDiff = curr.x - prev.x;
int yDiff = curr.y - prev.y;
if(xDiff == 0 && yDiff == 0){ // Same Location
path.append('!');
}
if(xDiff > 0){ // Go Down
appendNTimes(path, 'D', xDiff);
} else if(xDiff < 0){ // Go Up
appendNTimes(path, 'U', Math.abs(xDiff));
}
if(yDiff > 0){ // Go Right
appendNTimes(path, 'R', yDiff);
} else if(yDiff < 0){ // Go Left
appendNTimes(path, 'L', Math.abs(yDiff));
}
return path.toString();
}
private void appendNTimes(StringBuilder path, char direction, int n){
for(int i = 0; i < n; i++){
path.append(direction);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment