标签:
public class Solution { public boolean exist(char[][] board, String word) { if (board == null || board.length == 0) { return false; } if (word.length() == 0) { return true; } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { boolean res = dfs(board, word, 0, i, j); if (res) { return true; } } } } return false; } public boolean dfs(char[][] board, String word, int start, int i, int j) { if (word.length() == start) { return true; } if (i < 0 || j < 0 || j >= board[0].length || i >= board.length || word.charAt(start) != board[i][j]) { return false; } board[i][j] = ‘#‘; boolean res = dfs(board, word, start+1, i, j+1) || dfs(board, word, start+1, i, j-1) || dfs(board, word, start+1, i+1, j) || dfs(board, word, start+1, i-1, j); board[i][j] = word.charAt(start); return res; } }
dfs
参考:九章答案:http://www.jiuzhang.com/solutions/word-search/
code ganker
http://www.cnblogs.com/springfor/p/3883942.html
标签:
原文地址:http://www.cnblogs.com/77rousongpai/p/4519052.html