LeetCode 079 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 =

[

[‘A’,’B’,’C’,’E’],
[‘S’,’F’,’C’,’S’],
[‘A’,’D’,’E’,’E’]

]
word = “ABCCED“, -> returns true,
word = “SEE“, -> returns true,
word = “ABCB“, -> returns false.

分析

典型问题,回溯法(深度优先搜索DFS),暴力破解。以每一个字符为起点,分别判断上下左右四个字符是否符合条件。符合条件则一直向下寻找,否则回退。

代码

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

        if (board == null || board[0].length == 0 || board.length == 0
                || word == null) {
            return false;
        }

        int rows = board.length;
        int cols = board[0].length;
        boolean[] visited = new boolean[rows * cols];

        int pathLength = 0;
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {

                // 以row,col为开始,能够遍历得到结果
                if (dfs(board, rows, cols, row, col, word, pathLength, visited)) {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean dfs(char[][] board, int rows, int cols, int row,
            int col, String word, int pathLength, boolean[] visited) {

        // 如果pathLength的长度已经是查找字串的长度,则已经找到
        if (pathLength == word.length()) {
            return true;
        }

        boolean hasPath = false;

        // 符合条件的情况:
        // 1. 行、列均在矩阵范围内
        // 2. board[row][col]是所要找的字符
        // 3. board[row][col]没有遍历过
        if (row >= 0 && row < rows && col >= 0 && col < cols
                && board[row][col] == word.charAt(pathLength)
                && !visited[row * cols + col]) {

            pathLength++;
            visited[row * cols + col] = true;

            hasPath = dfs(board, rows, cols, row, col - 1, word, pathLength,
                    visited)
                    || dfs(board, rows, cols, row - 1, col, word, pathLength,
                            visited)
                    || dfs(board, rows, cols, row, col + 1, word, pathLength,
                            visited)
                    || dfs(board, rows, cols, row + 1, col, word, pathLength,
                            visited);

            // 若board[row][col]的前后左右没有满足条件的字符,则回退
            if (!hasPath) {
                pathLength--;
                visited[row * cols + col] = false;
            }
        }

        return hasPath;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值