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 }
  • 相关阅读:
    洛谷1509 找啊找啊找GF
    要怎样努力,才能成为很厉害的人?
    随笔
    2018NOIP模拟题 曲线
    洛谷4147 玉蟾宫
    洛谷2258 子矩阵
    Vijos 纸牌
    [leetcode] Word Break
    [leetcode] Maximum Binary Tree
    [leetcode] Binary Tree Preorder Traversal
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873345.html
Copyright © 2011-2022 走看看