码迷,mamicode.com
首页 > 其他好文 > 详细

79 Word Search

时间:2015-05-21 12:15:15      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:

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

79 Word Search

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4519052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!