From 43bcd24b2d47ff9b60eccedf7a6bb89c44b38cc4 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 6 Apr 2024 00:05:24 +0200 Subject: [PATCH] =?UTF-8?q?cs:=20add=20=C2=AB79.=20Word=20Search=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cs/word-search.cs | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 cs/word-search.cs diff --git a/cs/word-search.cs b/cs/word-search.cs new file mode 100644 index 0000000..80064f9 --- /dev/null +++ b/cs/word-search.cs @@ -0,0 +1,55 @@ +public class Solution { + private struct Solver { + char[][] Board { get; init; } + int Height { get => Board.Length; } + int Width { get => Board[0].Length; } + + string Word { get; init; } + + public Solver(char[][] board, string word) { + Board = board; + Word = word; + } + + private bool Has(int y, int x) + => y >= 0 && y < Height && x >= 0 && x < Width; + + private bool DFS(int y, int x, int i) { + if (i == Word.Length) { + return true; + } + + if (!Has(y, x) || Board[y][x] == '!' || Word[i] != Board[y][x]) { + return false; + } + + var tmp = Board[y][x]; + Board[y][x] = '!'; + + foreach (int d in new int[] { 1, -1 }) { + if (DFS(y + d, x, i + 1) || DFS(y, x + d, i + 1)) { + return true; + } + } + + Board[y][x] = tmp; + return false; + } + + public bool Solve() { + for (int y = 0; y < Height; ++y) { + for (int x = 0; x < Width; ++x) { + if (DFS(y, x, 0)) { + return true; + } + } + } + + return false; + } + } + + public bool Exist(char[][] board, string word) { + return new Solver(board, word).Solve(); + } +}