- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 55 lines of C++ from the credited upstream file 2018.cpp.
- The implementation visibly relies on sequence storage.
- 9 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 bool placeWordInCrossword(vector<vector<char>>& board, string word) {4 for (const vector<vector<char>>& state : {board, getRotated(board)})5 for (const vector<char>& chars : state)6 for (const string& token : getTokens(join(chars)))7 for (const string& letters :8 {word, string{word.rbegin(), word.rend()}})9 if (letters.length() == token.length())10 if (canFit(letters, token))11 return true;12 return false;13 }14 15 private:16 vector<vector<char>> getRotated(const vector<vector<char>>& board) {17 const int m = board.size();18 const int n = board[0].size();19 vector<vector<char>> rotated(n, vector<char>(m));20 for (int i = 0; i < m; ++i)21 for (int j = 0; j < n; ++j)22 rotated[j][i] = board[i][j];23 return rotated;24 }25 26 vector<string> getTokens(const string& row) {27 vector<string> tokens;28 int start = 0;29 int end;30 string token;31 do {32 end = row.find('#', start);33 token = row.substr(start, end - start);34 if (!token.empty())35 tokens.push_back(token);36 start = end + 1;37 } while (end != string::npos);38 return tokens;39 }40 41 string join(const vector<char>& chars) {42 string joined;43 for (const char c : chars)44 joined += c;45 return joined;46 }47 48 bool canFit(const string& letters, const string& token) {49 for (int i = 0; i < letters.length(); ++i)50 if (token[i] != ' ' && token[i] != letters[i])51 return false;52 return true;53 }54};55