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.

java代码:

  1. boolean[][] visited;
  2. boolean helper(char[][] board,String word,int start,int x,int y) {
  3. if(start==word.length()) {
  4. return true;
  5. }
  6. if(x>=board.length || y>=board[0].length) return false;
  7. if(x<0 || y<0) return false;
  8. if(visited[x][y]) return false;
  9. char cur = word.charAt(start);
  10. if(cur!=board[x][y]) return false;
  11. visited[x][y] = true;  // 保证不会回退访问  ["AA"]  ["AAA"] result =  false
  12. boolean res = helper(board,word,start+1,x,y+1) ||
  13. helper(board,word,start+1,x,y-1) ||
  14. helper(board,word,start+1,x+1,y) ||
  15. helper(board,word,start+1,x-1,y);
  16. visited[x][y]=false;
  17. return res;
  18. }
  19. public boolean exist(char[][] board, String word) {
  20. if(word==null) return true;
  21. int wlen = word.length();
  22. int w = board.length;
  23. if(w==0) return wlen==0;
  24. int h = board[0].length;
  25. if(h==0) return wlen==0;
  26. visited = new boolean[w][h];
  27. for(int i=0;i<w;i++) {
  28. for(int j=0;j<h;j++) {
  29. if(board[i][j] == word.charAt(0)) {
  30. if(helper(board,word,0,i,j)) {
  31. return true;
  32. }
  33. }
  34. }
  35. }
  36. return false;
  37. }
posted @ 2014-07-25 11:31  purejade  阅读(118)  评论(0)    收藏  举报