[关闭]
@ysongzybl 2015-05-25T20:07:27.000000Z 字数 1259 阅读 973

Summary: Problems solved by DFS III : Graph

interview


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 boolean dfs(char [][] board, String word, int cur_idx, int i, int j, boolean[][] visited){
  2. int m = board.length, n = board[0].length;
  3. if(i<0||j<0||i==m||j==n) return false;
  4. if(visited[i][j]) return false;
  5. if(board[i][j]!=word.charAt(cur_idx)) return false;
  6. if(cur_idx==word.length()-1) return true; // mistake : cur_idx == word.length() -> outrange error
  7. visited[i][j] = true;
  8. boolean found = false;
  9. found = dfs(board, word, cur_idx+1, i+1, j, visited) ||
  10. dfs(board, word, cur_idx+1, i-1, j, visited) ||
  11. dfs(board, word, cur_idx+1, i, j+1, visited) ||
  12. dfs(board, word, cur_idx+1, i, j-1, visited);
  13. visited[i][j] = false;
  14. return found;
  15. }
  16. public boolean exist(char[][] board, String word) {
  17. int m = board.length;
  18. if(m==0) return word.length()==0;
  19. int n = board[0].length;
  20. for(int i=0; i<m ; i++){
  21. for(int j=0; j<n; j++){
  22. boolean visited [][] = new boolean[m][n];
  23. if( dfs(board, word, 0, i, j, visited)) return true;
  24. }
  25. }
  26. return false;
  27. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注