LeetCode 79. Word Search

来源:互联网 发布:淘宝回收手机吗 编辑:程序博客网 时间:2024/05/17 07:02

问题描述

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.

问题描述

给定一个二维数组,求这个数组四个方向的探索,是否存在当前字符串。
从二维数组的每一个位置开始探索,然后从当前位出发,向四个方向探索,如果比对了String中所有的值就返回true。如果出现了不一致就直接返回fasle,然后进回溯。

代码实现

 /**     * 给定一个二维的数组,给定一个支付串,求这个支付串在这个二维数组中是否存在。     *     * @param board     * @param word     * @return     */    public boolean exist(char[][] board, String word) {        for (int i = 0; i < board.length; i++) {            for (int j = 0; j < board[i].length; j++) {                if (isExit(board, word, i, j, 0)) {                    return true;                }            }        }        return false;    }    /**     * 判断word中第index在二维数组中board中 i,j是否相等。如果相等就继续探索下一个,如果不等就结束     *     * @param board 二维数组     * @param word  支付串     * @param i     i的位置     * @param j     j的位置     * @param index 第index的位置     * @return 是否相等。如果相等     */    private boolean isExit(char[][] board, String word, int i, int j, int index) {        if (index == word.length()) {            return true;        }        if (i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(index)) {            return false;        }        board[i][j] ^= 128;//标识已经判断过了。        boolean exist = isExit(board, word, i + 1, j, index + 1) ||                isExit(board, word, i - 1, j, index + 1) ||                isExit(board, word, i, j + 1, index + 1) ||                isExit(board, word, i, j - 1, index + 1);        board[i][j] ^= 128;        return exist;    }
原创粉丝点击