Created
September 22, 2018 07:44
-
-
Save jianminchen/82f0094db413d62e15b6e0097e5cfc3e to your computer and use it in GitHub Desktop.
Mock interview - I was the interviewee
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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. | |
Input: | |
words = ["oath","pea","eat","rain"] and board = | |
[ | |
['o','a','a','n'], | |
['e','t','a','e'], | |
['i','h','k','r'], | |
['i','f','l','v'] | |
] | |
Output: ["eat","oath"] | |
letter | |
a b c .............z | |
o p | |
/ / | |
a e | |
/ / | |
t | |
/ | |
h | |
e | |
/ | |
a | |
/ | |
t | |
r | |
/ | |
a | |
/ | |
i | |
/ | |
n | |
constraint: | |
*/ | |
using System; | |
// To execute C#, please define "static void Main" on a class | |
// named Solution. | |
class Solution | |
{ | |
static void Main(string[] args) | |
{ | |
for (var i = 0; i < 5; i++) | |
{ | |
Console.WriteLine("Hello, World"); | |
} | |
} | |
internal class Trie | |
{ | |
public char Symbol{get; set;} | |
public Trie[26] Children {get; set;} | |
bool IsWord {get; set;} | |
public Trie() | |
{ | |
// | |
} | |
// add | |
// search | |
} | |
/// | |
public static IList<string> FindWords(char[,] board, string[] words) { | |
if(board == null || words == null) | |
return new List<string>(); | |
var dummyNode = new Trie(); // letter -> | |
putAllWordInTrie(dummyNode, words); | |
var rows = board.GetLength(0); | |
var cols = board.GetLength(1); | |
var wordsFound = new List<string>(); | |
/// | |
var visited = new bool[rows,cols]; //visited true/ false, 0, 1, 2 | |
for(int row = 0 ; row < rows; row++) | |
{ | |
for(int col = 0; col < cols; col++) | |
{ | |
var current = visited[row, col]; | |
if(current) | |
continue; | |
searchTrie(dummyNode, row, col, visited, board, wordsFound); | |
} | |
} | |
return wordsFound; | |
} | |
private static searchTrie(Trie dummyNode, int startRow, int startCol, bool[,] visited, char[,] board, IList<string> wordsFound) | |
{ | |
var current = board[startRow, startCol]; | |
// | |
var next = dummyNode.Children[current - 'a']; | |
if(next == null) | |
return; | |
if(next.IsWord) | |
{ | |
wordsFound.Add(); // words | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment