[Matrix]v79. Word Search

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

class Solution {

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

        int m = board.length;

        int n = board[0].length;

        for(int i = 0; i < m; i++) {

            for(int j = 0; j < n; j++){

                if (dfs(board, i, j, word, 0)) {

                    return true;

                }

            }

        }

        return false;

    }


    private boolean dfs(char[][] board, int i, int j, String word ,int index) {

        if (word.length() == index ) {

            return true;

        }

        if (i < 0 || i >= board.length

            || j < 0 || j >= board[0].length

            ||board[i][j] != word.charAt(index)

            ||board[i][j] == '+') {

            return false;

        }

        char tmp = board[i][j];

        board[i][j] = '+';

        boolean res =  dfs(board, i + 1, j, word, index+1)

            || dfs(board, i - 1, j, word, index+1)

            || dfs(board, i, j + 1, word, index+1)

            || dfs(board, i, j - 1, word, index+1);

        board[i][j] = tmp;

        return res;

    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容