-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordSearch.cs
More file actions
78 lines (68 loc) · 2.32 KB
/
WordSearch.cs
File metadata and controls
78 lines (68 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode.BackTrack
{
[TestClass]
public class Solution
{
public IList<string> FindWords(char[][] board, string[] words)
{
var list = new List<string>();
for (int i = 0; i < words.Length; i++)
{
if (IsWordExists(words[i], board))
{
list.Add(words[i]);
}
}
return list;
}
private bool IsWordExists(string word, char[][] board)
{
int index = 0;
for (int i = 0; i < board.Length; i++)
{
for (int j = 0; j < board.GetLength(i); j++)
{
return IsWordExistsHelper(word, board, i, j, index);
}
}
return false;
}
private bool IsWordExistsHelper(string word, char[][] board, int i, int j, int index)
{
if (index == word.Length)
{
return true;
}
if (i < 0 || i >= board.Length -1 || j < 0 || j >= board[i].Length - 1 || board[i][j] != word[index])
{
return false;
}
char temp = board[i][j];
board[i][j] = ' ';
index = index + 1;
bool found = IsWordExistsHelper(word, board, i + 1, j, index) ||
IsWordExistsHelper(word, board, i - 1, j, index) ||
IsWordExistsHelper(word, board, i, j + 1, index) ||
IsWordExistsHelper(word, board, i, j - 1, index);
board[i][j] = temp;
return found;
}
[TestMethod]
public void TestMethod()
{
char[][] board = { new char[]{ 'o', 'a', 'a', 'n' },
new char[] { 'e', 't', 'a', 'e' },
new char[]{ 'i', 'h', 'k', 'r' },
new char[]{ 'i', 'f', 'l', 'v' }
};
string[] words = { "oath", "pea", "eat", "rain" };
var listWords = this.FindWords(board, words);
}
}
}