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:
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.
题意:
给定一个字母矩阵,允许从任一点出发四处走。看轨迹能否构成一个单词。
1 class Solution { 2 public boolean exist(char[][] board, String word) { 3 for(int i = 0; i< board.length; i++){ 4 for(int j = 0; j < board[0].length; j++){ 5 if(helper(word, 0, board, i, j)){ 6 return true; 7 } 8 } 9 } 10 return false; 11 } 12 13 private boolean helper(String word, int index, char[][]board, int i, int j){ 14 // base case 15 if(index == word.length()){ 16 return true; 17 } 18 // 1. out of bound 2. char doesn't match 19 if( i < 0 || i >= board.length || j < 0 || j >= board[0].length || word.charAt(index) != board[i][j]){ 20 return false; 21 } 22 23 // save current character data and make a flag here 24 char temp = board[i][j]; 25 board[i][j] = '0'; 26 boolean found = helper (word, index+1, board, i+1, j) 27 ||helper (word, index+1, board, i-1, j) 28 ||helper (word, index+1, board, i, j-1) 29 ||helper (word, index+1, board, i, j+1); 30 // dismiss flag 31 board[i][j] = temp; 32 return found; 33 } 34 }