zoukankan      html  css  js  c++  java
  • [leetcode]79. 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 neighboring. The same letter cell may not be used more than once.

    Example:

    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.

    题意:

    给定一个字母矩阵,允许从任一点出发四处走。看轨迹能否构成一个单词。

     1 class Solution {
     2     public boolean exist(char[][] board, String word) {
     3         for(int i = 0; i< board.length; i++){
     4             for(int j = 0; j < board[0].length; j++){
     5                 if(helper(word, 0, board, i, j)){
     6                     return true;
     7                 }
     8             }
     9         }
    10         return false;
    11     }
    12     
    13     private boolean helper(String word, int index, char[][]board, int i, int j){
    14         // base case
    15         if(index == word.length()){
    16             return true;
    17         }
    18         // 1. out of bound  2. char doesn't match
    19         if( i < 0 || i >= board.length || j < 0 || j >= board[0].length || word.charAt(index) != board[i][j]){
    20             return false;
    21         }
    22         
    23         // save current character data and make a flag here 
    24         char temp = board[i][j];
    25         board[i][j] = '0';
    26         boolean found = helper (word, index+1, board, i+1, j) 
    27                         ||helper (word, index+1, board, i-1, j) 
    28                         ||helper (word, index+1, board, i, j-1) 
    29                         ||helper (word, index+1, board, i, j+1); 
    30        // dismiss flag
    31        board[i][j] = temp;
    32        return found;         
    33     }  
    34 }
  • 相关阅读:
    [SHOI2015]零件组装机
    [AH2017/HNOI2017]影魔
    空指针RE第一次公开赛-笔记
    i春秋2020新春公益赛WP
    博客园Markdown编辑器修改代码配色、添加代码行号
    buuctf Writeup
    关于Tarjan的一些问题
    NOIP2013D1T3货车运输 (生成树+树链剖分)
    1051: [HAOI2006]受欢迎的牛 (tarjan强连通分量+缩点)
    CodeForces 438D The Child and Sequence (线段树 暴力)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873345.html
Copyright © 2011-2022 走看看