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 }
  • 相关阅读:
    MySQL 之 索引原理与慢查询优化
    MySQL 之【视图】【触发器】【存储过程】【函数】【事物】【数据库锁】【数据库备份】
    MySQL 之 数据操作
    MySQL 之 表操作
    MySQL 之 库操作
    MySQL 之 基本概念
    MySQL 练习2
    MySQL 练习
    MySQL 环境搭建之解压方式安装
    python3 下载必应每日壁纸(三)
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/10873345.html
Copyright © 2011-2022 走看看