首页 > 其他 > 详细

Word Search

时间:2017-07-15 19:24:28      阅读:316      评论:0      收藏:0      [点我收藏+]

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.

考察:DFS 递归---回溯

public class Solution {
    /**
     * @param board: A list of lists of character
     * @param word: A string
     * @return: A boolean
     */
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length == 0 || board[0].length == 0) {
            return false;
        }
        if (word.length() == 0) {
            return true;
        }
        boolean result = false;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    result = findWord(board, i, j, word, 0);
                    if (result == true) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
    
    private boolean findWord(char[][] board, int i, int j, String word, int start) {
        if (start == word.length()) {
            return true;
        }
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || 
            board[i][j] != word.charAt(start)) {
            return false;
        }
        board[i][j] = ‘#‘;
        boolean result = findWord(board, i - 1, j, word, start + 1) || 
           findWord(board, i + 1, j , word, start + 1) || 
           findWord(board, i, j - 1, word, start + 1) || 
           findWord(board, i, j + 1, word, start + 1);
        board[i][j] = word.charAt(start);
        return result;
    }
}

 

Word Search

原文:http://www.cnblogs.com/FLAGyuri/p/7183887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!