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 }
  • 相关阅读:
    Python 安装、循环语句、数据类型(一)
    Python 字符、整型、列表字典等操作(二)
    JAVA实现文章的上一篇下一篇
    什么是公钥、私钥、密码、助记词
    XSS跨站网络攻击
    区块链相关知识
    冷钱包
    .NET 后台提交POST请求
    邮件的发送
    数据库中字段类型对应的C#中的数据类型
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873345.html
Copyright © 2011-2022 走看看