Skip to content

2018. Check if Word Can Be Placed In Crossword

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
 public:
  bool placeWordInCrossword(vector<vector<char>>& board, string word) {
    for (const vector<vector<char>>& state : {board, getRotated(board)})
      for (const vector<char>& chars : state)
        for (const string& token : getTokens(join(chars)))
          for (const string& letters :
               {word, string{word.rbegin(), word.rend()}})
            if (letters.length() == token.length())
              if (canFit(letters, token))
                return true;
    return false;
  }

 private:
  vector<vector<char>> getRotated(const vector<vector<char>>& board) {
    const int m = board.size();
    const int n = board[0].size();
    vector<vector<char>> rotated(n, vector<char>(m));
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        rotated[j][i] = board[i][j];
    return rotated;
  }

  vector<string> getTokens(const string& row) {
    vector<string> tokens;
    int start = 0;
    int end;
    string token;
    do {
      end = row.find('#', start);
      token = row.substr(start, end - start);
      if (!token.empty())
        tokens.push_back(token);
      start = end + 1;
    } while (end != string::npos);
    return tokens;
  }

  string join(const vector<char>& chars) {
    string joined;
    for (const char c : chars)
      joined += c;
    return joined;
  }

  bool canFit(const string& letters, const string& token) {
    for (int i = 0; i < letters.length(); ++i)
      if (token[i] != ' ' && token[i] != letters[i])
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
  public boolean placeWordInCrossword(char[][] board, String word) {
    for (char[][] state : new char[][][] {board, getRotated(board)})
      for (char[] chars : state)
        for (final String token : String.valueOf(chars).split("#"))
          for (final String letters :
               new String[] {word, new StringBuilder(word).reverse().toString()})
            if (letters.length() == token.length())
              if (canFit(letters, token))
                return true;
    return false;
  }

  private char[][] getRotated(char[][] board) {
    final int m = board.length;
    final int n = board[0].length;
    char[][] rotated = new char[n][m];
    for (int i = 0; i < m; ++i)
      for (int j = 0; j < n; ++j)
        rotated[j][i] = board[i][j];
    return rotated;
  }

  private boolean canFit(final String letters, final String token) {
    for (int i = 0; i < letters.length(); ++i)
      if (token.charAt(i) != ' ' && token.charAt(i) != letters.charAt(i))
        return false;
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def placeWordInCrossword(self, board: list[list[str]], word: str) -> bool:
    for x in board, zip(*board):
      for row in x:
        for token in ''.join(row).split('#'):
          for letters in word, word[::-1]:
            if len(token) == len(letters):
              if all(c in (' ', letter) for c, letter in zip(token, letters)):
                return True
    return False