个人记录-LeetCode 79. Word Search

来源:互联网 发布:java程序员初学者流程 编辑:程序博客网 时间:2024/06/01 10:29

问题:
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.

注意题干的“sequentially”, 即匹配方向是连续的,不走回头路。
于是这个问题暴力递归即可。

代码示例:

public class Solution {    public boolean exist(char[][] board, String word) {        if (board == null) {            return false;        }        //用于记录每个字符是否已经匹配过        boolean[][] bitMap = 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 (existInner(board, i, j, bitMap, word, 0)) {                    return true;                }            }        }        return false;    }    private boolean existInner(char[][] board, int i, int j, boolean[][] bitMap, String word, int next) {        //匹配完毕        if (next == word.length()) {            return true;        }        if (i >= board.length || i < 0 || j >= board[0].length || j < 0) {            return false;        }        //不相等,或已经匹配过        if (board[i][j] != word.charAt(next) || bitMap[i][j]) {            return false;        }        bitMap[i][j] = true;        //向当前位置的四周继续匹配        boolean rst = existInner(board, i+1, j, bitMap, word, next+1) ||                existInner(board, i-1, j, bitMap, word, next+1) ||                existInner(board, i, j+1, bitMap, word, next+1) ||                existInner(board, i, j-1, bitMap, word, next+1);        if (!rst) {            //需要复位            bitMap[i][j] = false;        }        return rst;    }}
0 0
原创粉丝点击