国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 个人记录-LeetCode 79. Word Search

个人记录-LeetCode 79. Word Search

来源:程序员人生   发布时间:2017-03-09 09:14:43 阅读次数:3022次

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

        //向当前位置的4周继续匹配
        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;
    }
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生