Word Search

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 =

[
  ["ABCE"],
  ["SFCS"],
  ["ADEE"]
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

 1 public class Solution {
 2     public boolean exist(char[][] board, String word) {
 3         if(word.length()==0) return true;
 4         boolean [][] visited = new boolean[row][col];
 5         for(int i=0;i<9;i++)
 6             for(int j=0;j<col;j++){
 7                 if(board[i][j]==word.charAt(0)){
 8                     boolean res = helper(board,visited,word,0,i,j);
 9                     if(res)return true;
10                 }
11         }
12         return false;
13     }
14     public boolean helper(char[][]board,boolean[][] visited,String word,int depth,int i,int j){
15         if(i<0||i>=board.length||j<0||j>=board[0].length||word.charAt(depth)!=board[i][j]||visited[i][j]) 
16             return false;
17         visited[i][j]=true;
18         if(depth==word.length()-1)return true;
19         boolean res = helper(board,visited,word,depth+1,i+1,j)||
20                       helper(board,visited,word,depth+1,i-1,j)||
21                       helper(board,visited,word,depth+1,i,j+1)||
22                       helper(board,visited,word,depth+1,i,j-1);
23         visited[i][j]=false;
24         return res;
25     }
26 }
View Code

         if(start==word.length()-1) return true;

posted @ 2014-02-06 14:39  krunning  阅读(122)  评论(0编辑  收藏  举报