void Recur(char[,] board, Trie tr, int curi, int curj, bool[,] map, int maxm, int maxn, List<string> re, string str) { if (curi >= maxm || curi < 0 || curj >= maxn || curj < 0 || map[curi, curj]) return; string newstr = str + board[curi, curj]; if (!tr.StartsWith(newstr)) return; if (tr.Search(newstr) && !re.Contains(newstr)) { re.Add(newstr); } map[curi, curj] = true; Recur(board, tr, curi + 1, curj, map, maxm, maxn, re, newstr); Recur(board, tr, curi - 1, curj, map, maxm, maxn, re, newstr); Recur(board, tr, curi, curj + 1, map, maxm, maxn, re, newstr); Recur(board, tr, curi, curj - 1, map, maxm, maxn, re, newstr); map[curi, curj] = false; return; }
public void TestTrieWord() { Trie t = new Trie(); t.Insert("hello"); t.Insert("he"); t.Insert("haw"); t.Insert("match"); t.Insert("yesterday"); Assert.IsTrue(t.Search("he")); Assert.IsTrue(t.Search("haw")); Assert.IsFalse(t.Search("mated")); Assert.IsFalse(t.Search("matches")); }
public static void Run() { Trie trie = new Trie(); trie.Insert("somestring"); Console.WriteLine(trie.Search("key")); trie.Insert("key1"); Console.WriteLine(trie.Search("key")); Console.WriteLine(trie.Search("key1")); Console.WriteLine(trie.StartsWith("some")); trie.Insert("abc"); Console.WriteLine(trie.Search("abc")); Console.WriteLine(trie.Search("ab")); trie.Insert("ab"); Console.WriteLine(trie.Search("ab")); trie.Insert("ab"); Console.WriteLine(trie.Search("ab")); }
public IList<string> FindWords(char[,] board, string[] words) { Trie tr = new Trie(); foreach (var w in words) tr.Insert(w); List<string> re = new List<string>(); int m = board.GetLength(0); int n = board.GetLength(1); bool[,] map = new bool[m, n]; StringBuilder sb = new StringBuilder(); for(int i=0; i< m; i++) for(int j=0; j< n; j++) { Recur(board, tr, i, j, map, m, n, re, ""); } return re; }