private void DFSHelper(char[,] matrix, int r, int c, int m, int n, bool[,] visited, TrieNode node, string prefix, IList <string> results) { if (!visited[r, c]) { visited[r, c] = true; string s = prefix + matrix[r, c]; TrieNode match = node.Search3(s); if (match != null) { if (match.LeafNode) { results.Add(s); } //string before = s; IList <IList <int> > neighbors = WordSearchHelper.GetValidNeighbors(matrix, r, c, m, n, visited); foreach (var neighbor in neighbors) { DFSHelper(matrix, neighbor[0], neighbor[1], m, n, visited, node, s, results); //sb = new StringBuilder(before); } } visited[r, c] = false; } }
private bool WordExistsHelper(char[,] matrix, int r, int c, int m, int n, string word, int index, bool[,] visited) { if (index == word.Length) { return(true); } if (matrix[r, c] == word[index]) { visited[r, c] = true; if (index == word.Length - 1) { return(true); } IList <IList <int> > neighbors = WordSearchHelper.GetValidNeighbors(matrix, r, c, m, n, visited); foreach (var neighbor in neighbors) { bool success = WordExistsHelper(matrix, neighbor[0], neighbor[1], m, n, word, index + 1, visited); if (success) { return(true); } } visited[r, c] = false; } return(false); }