leetcode Daily Challenge on July 21tg, 2020.
Difficulty : Medium
Related Topics : Array、BackTracking
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.
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.
board
andword
consists only of lowercase and uppercase English letters.1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
- 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; }
- Java