标签:
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.
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 // write your code here 7 8 if (board == null || board.length == 0 || board[0].length == 0) return false; 9 if (word.length() == 0) return true; 10 11 boolean[][] visited = new boolean[board.length][board[0].length]; 12 boolean[] result = new boolean[1]; 13 for (int i = 0; i < board.length; i++) { 14 for (int j = 0; j < board[0].length; j++) { 15 if (board[i][j] == word.charAt(0)) { 16 helper(board, i, j, word, 0, visited, result); 17 } 18 } 19 } 20 return result[0]; 21 } 22 23 public void helper(char[][] board, int i, int j, String word, int index, boolean[][] visited, boolean[] result) { 24 25 if (index == word.length()) { 26 result[0] = true; 27 } 28 29 if (result[0]) return; 30 31 if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; 32 33 if (visited[i][j] == false && board[i][j] == word.charAt(index)) { 34 visited[i][j] = true; 35 helper(board, i + 1, j, word, index + 1, visited, result); 36 helper(board, i - 1, j, word, index + 1, visited, result); 37 helper(board, i, j + 1, word, index + 1, visited, result); 38 helper(board, i, j - 1, word, index + 1, visited, result); 39 visited[i][j] = false; 40 } 41 } 42 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657088.html