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

Word Search

时间:2017-07-15 19:51:01      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:dfs   boolean   res   --   exists   vertica   int   turn   bool   

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

标签:dfs   boolean   res   --   exists   vertica   int   turn   bool   

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

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