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.
For example,
Given board =
12345 [["ABCE"],["SFCS"],["ADEE"]]word =
"ABCCED"
, -> returnstrue
,
word ="SEE"
, -> returnstrue
,
word ="ABCB"
, -> returnsfalse
.
Analysis
This is a recursive problem. What I use is some thing like DFS. A boolean array is used to save the visit states.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public class Solution { boolean[][] visited; public boolean exist(char[][] board, String word) { if (word.length() == 0) return true; int m = board.length; int n = board[0].length; visited = new boolean[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (search(board, word, 0, i, j)) return true; } } return false; } private boolean search(char[][] board, String word, int n, int i, int j) { if (n == word.length()) return true; if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return false; if (visited[i][j]) return false; if (word.charAt(n) != board[i][j]) return false; visited[i][j] = true; boolean result = search(board, word, n + 1, i - 1, j) || search(board, word, n + 1, i + 1, j) || search(board, word, n + 1, i, j - 1) || search(board, word, n + 1, i, j + 1); visited[i][j] = false; return result; } } |