【Leecode】Leecode刷题之路第79天之单词搜索

Scroll Down

题目出处

79-单词搜索-题目出处

题目描述

79-单词搜索-题目描述

个人解法

思路:

todo

代码示例:(Java)

todo

复杂度分析

todo

官方解法

79-单词搜索-官方解法

方法1:回溯

思路:

79-单词搜索-回溯-思路

代码示例:(Java)

public class Solution1 {
    public boolean exist(char[][] board, String word) {
        int h = board.length, w = board[0].length;
        boolean[][] visited = new boolean[h][w];
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                boolean flag = check(board, visited, i, j, word, 0);
                if (flag) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean check(char[][] board, boolean[][] visited, int i, int j, String s, int k) {
        if (board[i][j] != s.charAt(k)) {
            return false;
        } else if (k == s.length() - 1) {
            return true;
        }
        visited[i][j] = true;
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        boolean result = false;
        for (int[] dir : directions) {
            int newi = i + dir[0], newj = j + dir[1];
            if (newi >= 0 && newi < board.length && newj >= 0 && newj < board[0].length) {
                if (!visited[newi][newj]) {
                    boolean flag = check(board, visited, newi, newj, s, k + 1);
                    if (flag) {
                        result = true;
                        break;
                    }
                }
            }
        }
        visited[i][j] = false;
        return result;
    }


}

复杂度分析

79-单词搜索-回溯-复杂度分析

考察知识点

收获

Gitee源码位置

79-单词搜索-源码

同名文章,已同步发表于CSDN,个人网站,公众号