Leetcode

Leetcode 79

Word Search

Sailorlqh
2021-10-07
3 min

# 70. Climbing Stairs

Question link is here.

# Question

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:

img

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

img

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

img

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

# Solution

A very easy dfs question.

Start DFS at each coordinate the matches the word[0], and keep a visited map to track each coordinate that was visited earlier.

class Solution {
    char[][] board = null;
    String word = null;
    public boolean exist(char[][] b, String w) {
        board = b;
        word = w;
        boolean res = false;
        int[][] visited = new int[b.length][b[0].length];
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < board[0].length; j++) {
                if(board[i][j] == word.charAt(0)) {
                    res = helper(i, j, 0, visited);
                    if(res == true) {
                        return res;
                    }
                }
            }
        }
        return res;
    }
    
    public boolean helper(int x, int y, int index, int[][] visited) {
        if(x < 0 || x >= board.length || y < 0 || y >= board[0].length)
            return false;
        if(board[x][y] != word.charAt(index)) {
            return false;
        }
        if (visited[x][y] == 1) {
            return false;
        }
        if(index == word.length() - 1)
            return true;
        visited[x][y] = 1;
        if (helper(x+1, y, index+1, visited) 
            || helper(x-1, y, index+1, visited)
            || helper(x, y-1, index+1, visited)
            || helper(x, y+1, index+1, visited))
            return true;
        visited[x][y] = 0;
        return false;
    }
}