79. Word Search/212. Word Search II--图的back tracking -- tier tree 待续

79题,

给你一个二维的board, 只能往上下左右四个方向走,为你是否能找到单词。

board =
[
  [‘A‘,‘B‘,‘C‘,‘E‘],
  [‘S‘,‘F‘,‘C‘,‘S‘],
  [‘A‘,‘D‘,‘E‘,‘E‘]
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

分析: 算法并不难,从每个(i,j)为起点进行dfs, dfs 过程往上下左右四个方向走, 但不能走重复的节点,因此需要设置visted 来标记是否走过。      key point: 用visted 标记后,每次dfs 完后, 记得 visted 需要改成原来的value, 所谓的back tracking 就是体现在这里。

程序被我一开始写的太渣了:
class Solution {
    public boolean exist(char[][] board, String word) {

        int row = board[0].length;
        int col = board.length;

         boolean[][] visted = new boolean[col][row];
        for(int i=0; i<col; i++){
            for(int j=0; j<row; j++){
               // System.out.println("start: "+ i+ " "+ j);

                if(dfs(i,j,board,visted,word,0)) return true;
                visted[i][j] = false;
            }
        }
        return false;

    }

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

        if(board[i][j] != word.charAt(depth)) return false;

        if(depth == word.length()-1){
            return true;
        }

        boolean flag = false;

        visted[i][j] = true;
        //System.out.println(i+ " "+ j);
        //System.out.println(depth);

        //up
        if(i-1>=0&& !visted[i-1][j]){
            flag = flag || dfs(i-1,j,board,visted,word,depth+1);
            visted[i-1][j] = false;
            if(flag) return true;

        }
        //down
        if(i+1<board.length &&!visted[i+1][j]) {
            flag = flag || dfs(i+1,j,board,visted,word,depth+1);
            visted[i+1][j] = false;
            if(flag) return true;
        }
        //left
        if(j-1 >=0 && !visted[i][j-1]){
            flag = flag || dfs(i,j-1,board,visted,word,depth+1);
            visted[i][j-1] = false;
            if(flag) return true;
        }
        //right
        if(j+1<board[0].length&& !visted[i][j+1]){
           flag = flag ||  dfs(i,j+1,board,visted,word,depth+1);
           visted[i][j+1] = false;
           if(flag) return true;
        }

        return flag;
    }
}

又改成了:

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

        int row = board[0].length;
        int col = board.length;

         boolean[][] visted = new boolean[col][row];
        for(int i=0; i<col; i++){
            for(int j=0; j<row; j++){
               // System.out.println("start: "+ i+ " "+ j);

                if(dfs(i,j,board,visted,word,0)) return true;
               // visted[i][j] = false;
            }
        }
        return false;

    }

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

        if(board[i][j] != word.charAt(depth)) return false;

        if(depth == word.length()-1){
            return true;
        }

        boolean flag = false;

        visted[i][j] = true;
        //System.out.println(i+ " "+ j);
        //System.out.println(depth);

        //up
        if(i-1>=0&& !visted[i-1][j]){
            flag = flag || dfs(i-1,j,board,visted,word,depth+1);
           // visted[i-1][j] = false;

        }
        //down
        if(i+1<board.length &&!visted[i+1][j]) {
            flag = flag || dfs(i+1,j,board,visted,word,depth+1);
           // visted[i+1][j] = false;

        }
        //left
        if(j-1 >=0 && !visted[i][j-1]){
            flag = flag || dfs(i,j-1,board,visted,word,depth+1);
          //  visted[i][j-1] = false;

        }
        //right
        if(j+1<board[0].length&& !visted[i][j+1]){
           flag = flag ||  dfs(i,j+1,board,visted,word,depth+1);
          // visted[i][j+1] = false;

        }
        visted[i][j] = false;
        return flag;
    }
}

之所以写的不好,主要因为,应该把 边界条件和是否已经被访问 判断放在 下一次函数调用里,而不是本次里, 修改后的程序简单很多。

back traking 体现在 visted[i][j] = true ; dfs(...) ; visted[i][j] = false;

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

        int row = board[0].length;
        int col = board.length;

         boolean[][] visted = new boolean[col][row];
        for(int i=0; i<col; i++){
            for(int j=0; j<row; j++){
                if(dfs(i,j,board,visted,word,0)) return true;

            }
        }
        return false;

    }

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

        if(i<0 || j<0 || i >=board.length || j>=board[0].length ) return false; 

        if(board[i][j] != word.charAt(depth)) return false;

        if(visted[i][j]) return false;

        if(depth == word.length()-1){
            return true;
        }

         visted[i][j] = true;
         boolean flag =   dfs(i-1,j,board,visted,word,depth+1) ||dfs(i+1,j,board,visted,word,depth+1)
                       || dfs(i,j-1,board,visted,word,depth+1)|| dfs(i,j+1,board,visted,word,depth+1);

         visted[i][j] = false;
         return flag;
    }
}
212. Word Search II和79 基本雷同,给你 一个 string[] words, 要你找出 words 符合 79题搜索条件的单词。 如果用 dfs, 在 79题基础上加个for 循环就好了。但有个坑爹的地方: 字典: ["a"] words = ["a","a"] ,只能回 "a" ,而不能回 "a","a" 因此需要用set 存放结果。

更好的做法是用tier tree, 待续。

原文地址:https://www.cnblogs.com/keepAC/p/9972760.html

时间: 2024-07-29 15:29:55

79. Word Search/212. Word Search II--图的back tracking -- tier tree 待续的相关文章

Java for LeetCode 212 Word Search II

Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same le

Word Search 和 Word Search Ⅱ

Word Search 和 Word Search Ⅱ 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 neighbo

211 Add and Search Word - Data structure design--- back tracking, map, set 待续 trie

题意: 设计个字典查询系统, 有 add 和search 两种操作, add 是加入单词到字典里, search 时 可以用 点号通配符 ".", 点号可以匹配一个字母. 分析: 当search 时为 通配符时, 如果直接用back tracking产生 a-z, 比如 有7个点号, 就得生成  26^7 个组合,会TLE. 以下是TLE的code: class WordDictionary { /** Initialize your data structure here. */ S

leetcode Search a 2D Matrix II

题目连接 https://leetcode.com/problems/search-a-2d-matrix-ii/ Search a 2D Matrix II Description Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascend

【LeetCode】240. Search a 2D Matrix II

Search a 2D Matrix II Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascendin

LeetCode -- Search a 2D Matrix &amp; Search a 2D Matrix II

Question: Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the la

Search a 2D Matrix II【原创】

Search a 2D Matrix II: python学了还么两周可能有些地方写的很新手大家不要笑我 解题思路: 首先当数组为1维数组时if in 直接查找即可 当为 m x n 维数组时: matrix为行增列增的有序矩阵 所以对行和列采用折半查找,即可判断出值所在的新的矩阵范围,一步步缩小,若存在则某一次的行折半或者列折半肯定会遍历到,否则不存在于矩阵中 每一行的第一个元素为最小值,每一列最后一个元素为最大值 若此行的第一个元素比target要大,那肯定在行号小于此行的行中,若此列的最后

[LeetCode][JavaScript]Search a 2D Matrix II

Search a 2D Matrix II Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted in ascending from left to right. Integers in each column are sorted in ascendin

WORD文件如何在线转换成长图文件

WORD文件如何在线转换成长图文件,WORD文件内容转换成图片形式的话打开阅读会显得非常方便,而且可以将很长的一篇文档转换成长图,也减小了文件体积,那如何进行转换的呢. 点开百度首页,搜索关键词迅捷PDF在线转换器. 点开转换器页面,点击文档转换,选择Word转长图. 点击选择文件加入待转换的Word文件,也可直接拖动Word文件添加. 设置需要转换的页码等参数,点击开始转换,将自动上传转换文件. 转换需要几十秒的时间,耐心等待一下. 转换进度完成后,可选择直接打开也可以选择立即下载至桌面或文件