LeetCode-in-Net.github.io

Medium

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCCED”

Output: true

Example 2:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “SEE”

Output: true

Example 3:

Input: board = [[“A”,”B”,”C”,”E”],[“S”,”F”,”C”,”S”],[“A”,”D”,”E”,”E”]], word = “ABCB”

Output: false

Constraints:

Follow up: Could you use search pruning to make your solution faster with a larger board?

Solution

public class Solution {
    public bool Exist(char[][] board, string word) {
        for (int i = 0; i < board.Length; i++) {
            for (int j = 0; j < board[0].Length; j++) {
                char ch = word[0];
                if (board[i][j] == ch) {
                    if (helper(i, j, board, word, 1)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private bool helper(int r, int c, char[][] board, string word, int count) {
        if (count == word.Length) {
            return true;
        }
        char currChar = board[r][c];
        board[r][c] = '!';
        char nextChar = word[count];

        if (r > 0 && board[r - 1][c] == nextChar) {
            if (helper(r - 1, c, board, word, count + 1)) return true;
        }
        if (r < board.Length - 1 && board[r + 1][c] == nextChar) {
            if (helper(r + 1, c, board, word, count + 1)) return true;
        }
        if (c > 0 && board[r][c - 1] == nextChar) {
            if (helper(r, c - 1, board, word, count + 1)) return true;
        }
        if (c < board[0].Length - 1 && board[r][c + 1] == nextChar) {
            if (helper(r, c + 1, board, word, count + 1)) return true;
        }
        board[r][c] = currChar;
        return false;
    }
}