MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

cpp/Tries/find_all_words_on_a_board.cpp:47–71  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

45}
46
47void dfs(std::vector<std::vector<char>>& board, int r, int c, TrieNode* node, std::vector<std::string>& res) {
48 // If the current node represents the end of a word, add the word to
49 // the result.
50 if (!node->word.empty()) {
51 res.push_back(node->word);
52 // Ensure the current word is only added once.
53 node->word = "";
54 }
55 char temp = board[r][c];
56 // Mark the current cell as visited.
57 board[r][c] = '#';
58 // Explore all adjacent cells that correspond with a child of the
59 // current TrieNode.
60 std::vector<std::pair<int, int>> dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
61 for (auto& dir : dirs) {
62 int next_r = r + dir.first;
63 int next_c = c + dir.second;
64 if (isWithinBounds(next_r, next_c, board) &&
65 node->children.find(board[next_r][next_c]) != node->children.end()) {
66 dfs(board, next_r, next_c, node->children[board[next_r][next_c]], res);
67 }
68 }
69 // Backtrack by reverting the cell back to its original character.
70 board[r][c] = temp;
71}
72
73bool isWithinBounds(int r, int c, std::vector<std::vector<char>>& board) {
74 return r >= 0 && r < board.size() && c >= 0 && c < board[0].size();

Callers 1

findAllWordsOnABoardFunction · 0.70

Calls 2

isWithinBoundsFunction · 0.70
findMethod · 0.45

Tested by

no test coverage detected