I solved this programming challenge:
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]
word = "ABCCED", -> returns true
word = "SEE", -> returns true
word = "ABCB", -> returns false
class Solution {
public:
bool DFS(vector<vector<char>> &board, string word,
vector<vector<bool>> visited, int i, int j, int curr) {
if (i < 0 || j < 0 || i >= board.size() || j >= board[0].size()) {
return false;
}
if (visited[i][j] || board[i][j] != word[curr]) {
return false;
}
visited[i][j] = true;
++curr;
if (curr == word.size()) {
return true;
}
return DFS(board, word, visited, i + 1, j, curr) || // Down
DFS(board, word, visited, i, j + 1, curr) || // Right
DFS(board, word, visited, i - 1, j, curr) || // Up
DFS(board, word, visited, i, j - 1, curr); // Left
}
bool exist(vector<vector<char>> &board, string word) {
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board[i].size(); ++j) {
if (word[0] == board[i][j]) {
vector<vector<bool>> visited(board.size(),
vector<bool>(board[0].size(), false));
if (DFS(board, word, visited, i, j, 0)) {
return true;
}
}
}
}
return false;
}
};
My solution ranks at around 2% faster when compared to other solutions with the same language. My main desire from reviews are performance improvements.
visited
is passed by value, it should be correct. \$\endgroup\$std::vector<bool>
usesmemcpy()
and has small object optimization). If it allocates something on the heap, then certainly it will have considerable impact. \$\endgroup\$