Skip to content

Latest commit

 

History

History
83 lines (71 loc) · 2.17 KB

79. Word Search.md

File metadata and controls

83 lines (71 loc) · 2.17 KB

leetcode Daily Challenge on July 21tg, 2020.


Difficulty : Medium

Related Topics : ArrayBackTracking


Given a 2D board and a word, find if the word exists in the grid.

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

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

Solution

  • mine
    • Java
      • Runtime: 3 ms, faster than 99.92%, Memory Usage: 41.6 MB, less than 46.03% of Java online submissions
        // O(N + L)time in the worst case
        // O(1)space
        // L = word.length()
        // N = r * c
        public boolean exist(char[][] board, String word) {
            char[] arr = word.toCharArray();
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (dfs(board, arr, i, j, 0)) {
                        return true;
                    }
                }
            }
            return false;
        }
        
        boolean dfs(char[][] board, char[] word, int x, int y, int i) {
            char c = board[x][y];
            if (c == '#' || c != word[i]) {
                return false;
            }
            if (i + 1 == word.length) {
                return true;
            }
            board[x][y] = '#';
            i++;
            boolean res = (x > 0 && dfs(board, word, x - 1, y, i))
                    || (x + 1 < board.length && dfs(board, word, x + 1, y, i))
                    || (y > 0 && dfs(board, word, x, y - 1, i))
                    || (y + 1 < board[0].length && dfs(board, word, x, y + 1, i));
            board[x][y] = c;
            return res;
        }