标签:
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
Given board =
[ "ABCE", "SFCS", "ADEE" ]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
1 public class Solution { 2 /** 3 * cnblogs.com/beiyeqingteng/ 4 */ 5 public boolean exist(char[][] board, String word) { 6 if (board == null || board.length == 0 || board[0].length == 0) return false; 7 if (word.length() == 0) return true; 8 9 boolean[][] visited = new boolean[board.length][board[0].length]; 10 boolean[] result = new boolean[1]; 11 for (int i = 0; i < board.length; i++) { 12 for (int j = 0; j < board[0].length; j++) { 13 if (board[i][j] == word.charAt(0)) { 14 helper(board, i, j, word, 0, visited, result); 15 } 16 } 17 } 18 return result[0]; 19 } 20 21 public void helper(char[][] board, int i, int j, String word, int index, boolean[][] visited, boolean[] result) { 22 23 if (index == word.length()) { 24 result[0] = true; 25 } 26 27 if (result[0]) return; 28 29 if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; 30 31 if (visited[i][j] == false && board[i][j] == word.charAt(index)) { 32 visited[i][j] = true; 33 helper(board, i + 1, j, word, index + 1, visited, result); 34 helper(board, i - 1, j, word, index + 1, visited, result); 35 helper(board, i, j + 1, word, index + 1, visited, result); 36 helper(board, i, j - 1, word, index + 1, visited, result); 37 visited[i][j] = false; 38 } 39 } 40 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5625530.html