zoukankan      html  css  js  c++  java
  • *Word Search & by using 回溯法模板

    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

     1 public class Solution {
     2     // recursion
     3     public boolean exist(char[][] board, String word) {
     4         if(board == null || board.length == 0)
     5             return false;
     6         if(word.length() == 0)
     7             return true;
     8         
     9         for(int i = 0; i< board.length; i++){
    10             for(int j=0; j< board[0].length; j++){
    11                 if(board[i][j] == word.charAt(0)){
    12                     
    13                     boolean rst = find(board, i, j, word, 0);
    14                     if(rst)
    15                         return true;
    16                 }
    17             }
    18         }
    19         return false;
    20     }
    21     
    22     private boolean find(char[][] board, int i, int j, String word, int start){
    23         if(start == word.length())
    24             return true;
    25         
    26         if (i < 0 || i>= board.length || 
    27      j < 0 || j >= board[0].length || board[i][j] != word.charAt(start)){
    28             return false;
    29      }
    30         
    31         board[i][j] = '@'; // should remember to mark it
    32         boolean rst = (find(board, i-1, j, word, start+1) 
    33 || find(board, i, j-1, word, start+1) 
    34 || find(board, i+1, j, word, start+1) 
    35 || find(board, i, j+1, word, start+1));
    36         board[i][j] = word.charAt(start);
    37         return rst;
    38     }
    
                                                                                    


  • 相关阅读:
    [LeetCode每日1题][简单] 169. 多数元素
    [LeetCode每日1题][简单] 1013. 将数组分成和相等的三个部分
    [LeetCode每日1题][中等] 322. 零钱兑换
    [LeetCode每日1题][中等] 面试题59
    软工实践个人总结
    2019 SDN大作业
    2019 SDN上机第7次作业
    第01组 Beta版本演示
    如果有一天我变得很有钱组——alpha冲刺day7
    如果有一天我变得很有钱组——alpha冲刺day6
  • 原文地址:https://www.cnblogs.com/hygeia/p/4922266.html
Copyright © 2011-2022 走看看