关闭

Word Search

174人阅读 评论(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.

For example,
Given board =

[
[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]
]
word = “ABCCED”, -> returns true,
word = “SEE”, -> returns true,
word = “ABCB”, -> returns false.
Subscribe to see which companies asked this question

public class Solution {
    //this is a good problem
    public boolean exist(char[][] board, String word) {
        if(board == null || word == null || word.length() == 0)
            return false;

        for(int i =0; i < board.length; i ++) {
            for(int j = 0; j < board[0].length; j++) {
               if(dfs(board, i, j, word, 0, new boolean[board.length][board[0].length]))
                    return true;
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, int i, int j, String word, int index, boolean[][] isVisited) {
        if(word.length() == index)
            return true;
        if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index) || isVisited[i][j])
            return false;

        isVisited[i][j] = true;
        if(dfs(board, i - 1, j, word, index + 1, isVisited))
            return true;

        if( dfs(board, i + 1, j, word, index + 1, isVisited))
            return true;

        if( dfs(board, i, j - 1, word, index + 1, isVisited))
            return true;

        if( dfs(board, i, j + 1, word, index + 1, isVisited))
            return true;
        //this statement is equal to the four statement above 
       // boolean res = dfs(board, i - 1, j, word, index + 1, isVisited) || dfs(board, i + 1, j, word, index + 1, isVisited) ||
         //               dfs(board, i, j - 1, word, index + 1, isVisited) || dfs(board, i, j + 1, word, index + 1, isVisited);
        isVisited[i][j] = false;
        return false;
       // return res;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65768次
    • 积分:1299
    • 等级:
    • 排名:千里之外
    • 原创:70篇
    • 转载:19篇
    • 译文:0篇
    • 评论:2条
    最新评论