Skip to content

Commit

Permalink
Solve LeetCode #79 'Word Search' [Medium].
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Dec 6, 2024
1 parent 4dd8352 commit 61ba239
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
namespace LeetCode.Challenges.Problems00xx.N_0079_WordSearch;

public static class Solution
{
public static bool Exist(char[][] board, string word)
{
var rows = board.Length;
var cols = board[0].Length;
var visited = new bool[rows, cols];

for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (Dfs(row, col, 0))
{
return true;
}
}
}

return false;

bool Dfs(int i, int j, int index)
{
if (i < 0 || i >= rows || j < 0 || j >= cols || visited[i, j] || board[i][j] != word[index])
{
return false;
}

if (index == word.Length - 1)
{
return true;
}

visited[i, j] = true;

bool found =
Dfs(i + 1, j, index + 1) ||
Dfs(i - 1, j, index + 1) ||
Dfs(i, j + 1, index + 1) ||
Dfs(i, j - 1, index + 1);

visited[i, j] = false;

return found;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using LeetCode.Challenges.Problems00xx.N_0079_WordSearch;
using Shouldly;
using Xunit;

namespace LeetCode.Challenges.UnitTests.Problems00xx.N_0079_WordSearch;

public class SolutionTests
{
[Theory]
[MemberData(nameof(TestData))]
public void GivenNumbers_WhenSubsets_ThenResultAsExpected(char[][] board, string word, bool expectedResult)
{
Solution.Exist(board, word).ShouldBe(expectedResult);
}

public static IEnumerable<object[]> TestData()
{
yield return
[
new char[][]
{
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
},
"ABCCED",
true
];

yield return
[
new char[][]
{
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
},
"SEE",
true
];

yield return
[
new char[][]
{
[ 'A', 'B', 'C', 'E' ],
[ 'S', 'F', 'C', 'S' ],
[ 'A', 'D', 'E', 'E' ]
},
"ABCB",
false
];
}
}

0 comments on commit 61ba239

Please sign in to comment.