Leetcode -- Word Search

来源:互联网 发布:linux 修改密码 编辑:程序博客网 时间:2021/11/29 08:18

https://oj.leetcode.com/problems/word-search/


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 =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.


public boolean exist(char[][] board, String word)

这一题和后面有一题叫surrounded region的是有点类似的,本质是图论题。在每个点进行图的遍历,BFS或者DFS皆可。这一题首选DFS深度搜索,因为我们需要找到的是唯一一个单词,也就是深度搜索到一个路径匹配那个word就可以返回true了。BFS广度搜索更适合搜寻所有的路径,也就是这一题如果要求返回的不是boolean而是所有符合word的东西的话,广度搜索就会更加适合,所以在surrounded region那题我就用了BFS。另外这类题都需要用一种方式标记自己走过的地方,这里用的就是一个二维boolean矩阵,DFS比BFS便利的地方也在于它们比较容易维护和回收自己走过节点的标记。这样就不需要另外维护走过的标记

    public boolean exist(char[][] board, String word) {        boolean[][] visited = new boolean[board.length][board[0].length];        for(int i = 0; i < board.length; i++){            for(int j = 0; j < board[0].length; j++){                if(helper(visited, board, i, j, 0, word))                    return true;            }        }        return false;    }        public boolean helper(boolean[][] visited, char[][] board, int x, int y, int cur_len, String word){        if(x < 0 || x >= board.length || y < 0 || y >= board[0].length || visited[x][y])            return false;        if(word.charAt(cur_len) == board[x][y]){            if(cur_len == word.length() - 1)                return true;            visited[x][y] = true;            if(helper(visited, board, x - 1, y, cur_len + 1, word) || helper(visited, board, x + 1, y, cur_len + 1, word) || helper(visited, board, x, y + 1, cur_len + 1, word) || helper(visited, board, x, y - 1, cur_len + 1, word))                return true;            visited[x][y] = false;            return false;        }else            return false;    }


0 0