0
点赞
收藏
分享

微信扫一扫

Day43 单词搜索

给定一个二维网格和一个单词,找出该单词是否存在于网格中

https://leetcode-cn.com/problems/word-search/

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用

示例1:

提示:

Java解法

package sj.shimmer.algorithm.m2;

/**
 * Created by SJ on 2021/3/8.
 */

class D43 {

    public static void main(String[] args) {
//        System.out.println(exist(
//                new char[][]{
//                        new char[]{'A', 'B', 'C', 'E'},
//                        new char[]{'S', 'F', 'C', 'S'},
//                        new char[]{'A', 'D', 'E', 'E'}
//                }, "CESCC"));
        System.out.println(exist(
                new char[][]{
                        new char[]{'A','B', 'C', 'E'},
                        new char[]{'S','F', 'E', 'S'},
                        new char[]{'A','D', 'E', 'E'}
                },
                "ABCESEEEFS"));
//        System.out.println(exist(
//                new char[][]{
//                        new char[]{'A', 'B'},
//                }, "BA"));
    }
    public static boolean exist(char[][] board, String word) {
        if (board==null) {
            return false;
        }
        int rowLength = board.length;
        int columnLength = board[0].length;
        boolean[][] path = new boolean[rowLength][columnLength];
        for (int i = 0; i < rowLength; i++) {
            for (int j = 0; j < columnLength; j++) {
                boolean result = backTrace(board, path, i, j, word, 0);
                if (result) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean backTrace(char[][] board, boolean[][] path, int row, int column, String word, int index) {
        if (row < 0 || column < 0 || row >= board.length || column >= board[row].length) {
            return false;
        }
        if (path[row][column]) {//经历过
            return false;
        }
        if (word.charAt(index)!=board[row][column]) {
            return false;
        }else if (index == word.length()-1) {
            return true;
        }
        path[row][column] = true;//经历
        boolean result = backTrace(board, path, row - 1, column, word, index + 1) ||
                backTrace(board, path, row + 1, column, word, index + 1) ||
                backTrace(board, path, row, column - 1, word, index + 1) ||
                backTrace(board, path, row, column + 1, word, index + 1);
        path[row][column] = false;//恢复
        return result;
    }
}

官方解

https://leetcode-cn.com/problems/word-search/solution/dan-ci-sou-suo-by-leetcode-solution/

  1. 深度优先搜索

    • 时间复杂度:O(MN⋅3 ^L ) M,N 为网格的长度与宽度
  • 空间复杂度:O(MN)
举报

相关推荐

0 条评论