Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added solution.class
Binary file not shown.
67 changes: 67 additions & 0 deletions solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class solution {
public static boolean canMakeWord(char[][] board, String word) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == word.charAt(0)) {
if (helper(0, i, j, board, word)) {
return true;
}
}
}
}

return false;
}

private static boolean helper(int index, int i, int j, char[][] board, String word) {
if (i < 0 || j < 0 || i >= board.length || j >= board[i].length) { // out of bounds
return false;
} else if (board[i][j] != word.charAt(index)) { // wrong letter or already visited
return false;
} else if (index == word.length() - 1) { // found word
return true;
}

char c = board[i][j];
board[i][j] = 0;

if (helper(index + 1, i - 1, j, board, word) // up
|| helper(index + 1, i + 1, j, board, word) // down
|| helper(index + 1, i, j - 1, board, word) // left
|| helper(index + 1, i, j + 1, board, word)) { // right
return true;
}

board[i][j] = c; // backtrack

return false;
}

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

ArrayList<char[]> al = new ArrayList<char[]>();
String rawInput;
String word;

while (true) {
rawInput = br.readLine();
if (rawInput.split(" ").length != 1) {
al.add(rawInput.replace(" ", "").toCharArray());
} else {
word = rawInput;
break;
}
}

char[][] arr = new char[al.size()][];
arr = al.toArray(arr); // making into 2d array so its easier to work with

System.out.println(canMakeWord(arr, word));
}
}