Skip to content

added solution for 212 #154

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

Merged
merged 1 commit into from
Mar 11, 2021
Merged
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
40 changes: 40 additions & 0 deletions src/main/java/com/fishercoder/solutions/_212.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.fishercoder.solutions;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

public class _212 {
Expand Down Expand Up @@ -68,4 +69,43 @@ private TrieNode buildTrie(String[] words) {
return root;
}
}

public static class Solution2 {
public List findWords (char[][] board, String[] words) {

List result = new ArrayList();
HashSet set = new HashSet();
for (String word : words) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == word.charAt(0) && search(board, i, j, 0, word)) {
set.add(word);
}
}
}
}
result = new ArrayList<>(set);
return result;
}

private boolean search(char[][] board, int i, int j, int count, String word) {
if (count == word.length()) {
return true;
}

if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(count)) {
return false;
}

char temp = board[i][j];
board[i][j] = ' ';

boolean foundWord = search(board, i + 1, j, count + 1, word)
|| search(board, i - 1, j, count + 1, word)
|| search(board, i, j + 1, count + 1, word)
|| search(board, i, j - 1, count + 1, word);
board[i][j] = temp;
return foundWord;
}
}
}