zoukankan      html  css  js  c++  java
  • Backtracking_79. 单词搜索

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

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

    示例:

    board =
    [
    ['A','B','C','E'],
    ['S','F','C','S'],
    ['A','D','E','E']
    ]
    
    给定 word = "ABCCED", 返回 true
    给定 word = "SEE", 返回 true
    给定 word = "ABCB", 返回 false 

    提示:

    • board 和 word 中只包含大写和小写英文字母。
    • 1 <= board.length <= 200
    • 1 <= board[i].length <= 200
    • 1 <= word.length <= 10^3

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/word-search


    回溯问题,其实这题应该还是DFS的问题,定一个方向标找他四连通位置上的值有没有和给定的字符串一样的

    如果有,就再往下,如果发现此路不通就回溯

    class Solution {
        //定义一个方向标
        static final int[][] DIRS = new int[][]{{-1,0}, {1,0}, {0,-1},{0,1}};
        static int row , col;
        public static boolean exist(char[][] board, String word){
            //特殊情况判断
            if (board == null || board.length == 0 || board[0].length == 0){
                return false;
            }
            if (word.length() == 0){
                return true;
            }
            row = board.length;
            col = board[0].length;
            boolean [][] isVisited = new boolean[row][col];
            for (int i = 0; i < row; i++) {
                for (int j = 0; j < col; j++) {
                    if (dfs(0,i,j,board,isVisited,word)){
                        return true;
                    }
                }
            }
            return false;
        }
    
        public static boolean dfs(int curLen, int i ,int j, char [][] board, boolean [][] isVisited,String word){
            if (curLen == word.length()) {
                return true;
            }
            //排除所有的不符合的条件
            if (i < 0 || i >= row || j < 0 || j >= col || board[i][j] != word.charAt(curLen) || isVisited[i][j]) {
                return false;
            }
            //进来了就说明这个点已经访问过了
            isVisited[i][j] = true;
            for (int[] d : DIRS) {
                if (dfs(curLen + 1, i + d[0], j + d[1], board, isVisited, word)) {
                    return true;
                }
            }
            isVisited[i][j] = false;
            return false;
        }
    }
  • 相关阅读:
    测试
    微商就该这么加粉丝,你造吗?
    下拉刷新ListView实现原理
    android studio出现 waiting for adb
    发现一个很好的android开发笔记库
    android studio 不能在线更新android SDK Manager问题解决办法
    asp.net中XmlDocument解析出现出错,处理特殊字符
    假如是你,你会怎么选择
    winrt 上的翻书特效组件 源码分享 转载请说明
    在Windows8 Winrt中 高性能处理多个条件语句 用于实现自定义手势
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13370884.html
Copyright © 2011-2022 走看看