Content-Length: 16256 | pFad | https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0079_word_search

LeetCode in Net | C#-based LeetCode algorithm problem solutions, regularly updated.

LeetCode in Net

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;
    }
}








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: https://leetcode-in-net.github.io/LeetCodeNet/G0001_0100/S0079_word_search

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy