首页 > 代码库 > 212. Word Search II
212. Word Search II
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must 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 in a word.
For example,
Given words = ["oath","pea","eat","rain"]
and board =
[ [‘o‘,‘a‘,‘a‘,‘n‘], [‘e‘,‘t‘,‘a‘,‘e‘], [‘i‘,‘h‘,‘k‘,‘r‘], [‘i‘,‘f‘,‘l‘,‘v‘]]
Return ["eat","oath"]
.
Note:
You may assume that all inputs are consist of lowercase letters a-z
.
public class Solution { public IList<string> FindWords(char[,] board, string[] words) { var res = new List<string>(); if(words.Count() == 0 || board == null) return res; Trie trie = new Trie(); foreach(string word in words) { trie.Insert(word); } var visited = new bool[board.GetLength(0),board.GetLength(1)]; for(int i = 0;i<board.GetLength(0) ;i++) { for(int j = 0;j<board.GetLength(1) ;j++) { if(trie.Root.Child[board[i,j]-‘a‘] != null) { Search(board,trie.Root.Child[board[i,j]-‘a‘], visited,i,j,res,board[i,j]+""); } } } return res; } private void Search(char[,] board,TrieNode t, bool[,] visited, int row, int col,IList<string> res, string cur) { if(t != null && t.EndWord) { if(!res.Contains(cur))res.Add(cur); } if(row<0 || row >= board.GetLength(0)|| col<0 || col >= board.GetLength(1)) { return; } else { visited[row,col] = true; if(row>0 && !visited[row-1,col] && t.Child[board[row-1,col]-‘a‘] != null ) Search(board,t.Child[board[row-1,col]-‘a‘], visited, row-1, col,res, cur+board[row-1,col]); if(row<board.GetLength(0)-1 && !visited[row+1,col] && t.Child[board[row+1,col]-‘a‘] != null) Search(board,t.Child[board[row+1,col]-‘a‘], visited, row+1, col,res, cur+board[row+1,col]); if(col>0 &&!visited[row,col-1] && t.Child[board[row,col-1]-‘a‘] != null ) Search(board,t.Child[board[row,col-1]-‘a‘], visited, row, col-1,res, cur+board[row,col-1]); if(col<board.GetLength(1)-1 && !visited[row,col+1] && t.Child[board[row,col+1]-‘a‘] != null) Search(board,t.Child[board[row,col+1]-‘a‘], visited, row, col+1,res, cur+board[row,col+1]); visited[row,col] = false; } }}public class TrieNode { public TrieNode[] Child {get;set;} public bool EndWord {get;set;} public TrieNode() { Child = new TrieNode[26]; EndWord = false; } }public class Trie{ public TrieNode Root {get;set;} public Trie() { Root = new TrieNode(); } public void Insert(string word) { var sentinel = Root; foreach(char c in word) { if(sentinel.Child[c-‘a‘] == null) sentinel.Child[c-‘a‘] = new TrieNode(); sentinel = sentinel.Child[c-‘a‘]; } sentinel.EndWord = true; }}
212. Word Search II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。