[leetcode]79.Search Word 回溯法

/**
 * 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.
 */
/*
* 回溯法:递归加循环,找准时机回溯状态
* 定义一个数组记录当前位置有没有已经访问过,这个数组就是需要回溯的状态
* 把每个元素当做开头循环一遍,每次判断当前元素的上下左右,如果有符合条件的就再进入递归判断上下左右
* 直到判断到target的最后一个字符符合就返回true,每次把递归放在if的判断条件里,这样只要有一个true就会
* return出去,返回false就再换个位置继续判断
* 注意回溯的位置,是确定当前位置的上下左右都不可用时再回溯*/
public class Q79WordSearch {
    public static void main(String[] args) {
        char[][] board = new char[][]{{‘a‘,‘b‘,‘c‘,‘e‘},{‘s‘,‘f‘,‘c‘,‘s‘},{‘a‘,‘d‘,‘e‘,‘e‘}};
        String word = "abcced";
        Q79WordSearch q = new Q79WordSearch();
        System.out.println(q.exist(board,word));
    }
    public boolean exist(char[][] board, String word) {
        if (word.length() == 0)
            return true;
        //记录是否访问过的表格
        int[][] flag = new int[board.length][board[0].length];
        boolean res = false;
        //数组中的每个元素作为开头,遍历一次
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (gobacking(board,word,flag,i,j,0))
                    return true;
            }
        }
        return false;
    }
    public boolean gobacking(char[][] board,String word,int[][] flag,int row,int col,int num)
    {
        char ch = word.charAt(num);
        //越界或者访问过就返回
        if (row < 0 || row > board.length-1 || col < 0 ||col > board[0].length-1 || flag[row][col] == 1)
            return false;
        //不符合条件
        if (ch != board[row][col])
            return false;
        //符合条件,记录数组相应位置置1,代表访问过了
        flag[row][col] = 1;
        //如果最后一个位置的字母也相等,那就是符合条件了
        if (num == word.length()-1)
            return true;
        for (int i = -1;i <= 1;i++)
        {
            for (int j = -1; j <= 1; j++) {
//             只循环上下左右
                if (Math.abs(i) == Math.abs(j))
                    continue;
                //只有符合条件才会往下判断
                if (gobacking(board,word,flag,row+i,col+j,num+1))
                    return true;
            }
        }
        //执行到这里就是没有符合条件的,回溯,把此次的位置置0
        flag[row][col] = 0;
        //能执行到这里说明没有符合条件的
        return false;
    }
}
时间: 2024-12-17 05:45:18

[leetcode]79.Search Word 回溯法的相关文章

leetcode || 79、Word Search

problem: 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

【LeetCode】回溯法 backtracking(共39题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [10]Regular Expression Matching [17]Letter Combinations of a Phone Number [22]Generate Parentheses (2019年2月13日) 给了一个N,生成N对括号的所有情况的字符串. n = 3 [ "((()))", "(()())", "(

[LeetCode][JavaScript]Add and Search Word - Data structure design

Add and Search Word - Data structure design Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or 

[LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter

Java for LeetCode 211 Add and Search Word - Data structure design

Design a data structure that supports the following two operations: void addWord(word)bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

从Leetcode的Combination Sum系列谈起回溯法

在LeetCode上面有一组非常经典的题型--Combination Sum,从1到4.其实就是类似于给定一个数组和一个整数,然后求数组里面哪几个数的组合相加结果为给定的整数.在这个题型系列中,1.2.3都可以通过回溯法来解决,其实4也可以,不过由于递归地比较深,采用回溯法会出现TLE.因此本文只讨论前三题. 什么是回溯法?回溯法是一种选优搜索法,按选优条件向前搜索以达到目标.当探索到某一步时,发现原先的选择并不优或达不到目标,就退回异步重新选择.回溯法是深度优先搜索的一种,但回溯法在求解过程不

[Leetcode] Backtracking回溯法解题思路

碎碎念: 最近终于开始刷middle的题了,对于我这个小渣渣确实有点难度,经常一两个小时写出一道题来.在开始写的几道题中,发现大神在discuss中用到回溯法(Backtracking)的概率明显增大.感觉如果要顺利的把题刷下去,必须先要把做的几道题题总结一下. 先放上参考的web: https://segmentfault.com/a/1190000006121957 http://summerisgreen.com/blog/2017-07-07-2017-07-07-算法技巧-backtr

[LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计

Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter

[LeetCode] 211. Add and Search Word - Data structure design Java

题目: Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one le