212. Word Search II
Posted 咖啡中不塌缩的方糖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章