diff --git a/LeetCode/src/LeetCode.Challenges/Problems00xx/N_0079_WordSearch/Solution.cs b/LeetCode/src/LeetCode.Challenges/Problems00xx/N_0079_WordSearch/Solution.cs new file mode 100644 index 0000000..342d34e --- /dev/null +++ b/LeetCode/src/LeetCode.Challenges/Problems00xx/N_0079_WordSearch/Solution.cs @@ -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; + } + } +} diff --git a/LeetCode/tests/LeetCode.Challenges.UnitTests/Problems00xx/N_0079_WordSearch/SolutionTests.cs b/LeetCode/tests/LeetCode.Challenges.UnitTests/Problems00xx/N_0079_WordSearch/SolutionTests.cs new file mode 100644 index 0000000..3e603eb --- /dev/null +++ b/LeetCode/tests/LeetCode.Challenges.UnitTests/Problems00xx/N_0079_WordSearch/SolutionTests.cs @@ -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 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 + ]; + } +}