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 =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word =
"ABCB"
, -> returns false
.
public class Solution { private boolean result; private boolean[][] visited; public boolean exist(char[][] board, String word) { // Backtracking problem int m = board.length; if (m == 0) return false; int n = board[0].length; if (word.length() == 0) return true; result = false; visited = new boolean[m][n]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (board[i][j] == word.charAt(0)) { visited[i][j] = true; backTracking(board, word, i, j, 1); visited[i][j] = false; } return result; } private void backTracking(char[][] board, String word, int i, int j, int cnt) { if (cnt == word.length()) result = true; else { if (result) return; char c = word.charAt(cnt); if (i-1>=0 && !visited[i-1][j] && board[i-1][j]==c) { visited[i-1][j] = true; backTracking(board, word, i-1, j, cnt+1); visited[i-1][j] = false; } if (i+1<board.length && !visited[i+1][j] && board[i+1][j]==c) { visited[i+1][j] = true; backTracking(board, word, i+1, j, cnt+1); visited[i+1][j] = false; } if (j-1>=0 && !visited[i][j-1] && board[i][j-1]==c) { visited[i][j-1] = true; backTracking(board, word, i, j-1, cnt+1); visited[i][j-1] = false; } if (j+1<board[0].length && !visited[i][j+1] && board[i][j+1]==c) { visited[i][j+1] = true; backTracking(board, word, i, j+1, cnt+1); visited[i][j+1] = false; } } } }
No comments:
Post a Comment