zoukankan      html  css  js  c++  java
  • leetcode79 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.

    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 class Solution {
     2 public:
     3     bool exist(vector<vector<char>>& board, string word) {
     4         int m=board.size();
     5         if(!m)
     6             return false;
     7         int n=board[0].size();
     8         if(word.length()==0)
     9             return false;
    10         
    11         vector<bool> temp(n,false);
    12         vector<vector<bool>> mark;
    13         for(int i=0;i<m;i++)
    14             mark.push_back(temp);
    15         
    16         for(int i=0;i<m;i++)
    17         {
    18             for(int j=0;j<n;j++)
    19             {
    20                 if(board[i][j]==word[0])
    21                 {
    22                     mark[i][j]=true;
    23                     if(deep(board,mark,1,word,i,j))
    24                         return true;
    25                     mark[i][j]=false;
    26                 }
    27             }
    28         }
    29         return false;
    30     }
    31     bool deep(vector<vector<char>>& board,vector<vector<bool>> mark,int p,string word,int x,int y)
    32     {
    33         if(p>=word.length())
    34             return true;
    35         int dir[4][2]={
    36             {0,-1},
    37             {0,1},
    38             {-1,0},
    39             {1,0}
    40         };
    41         for(int i=0;i<4;i++)
    42         {
    43             int tx=x+dir[i][0];
    44             int ty=y+dir[i][1];
    45             if(tx<0||tx>=board.size()||ty<0||ty>=board[0].size()||mark[tx][ty]==true)
    46                 continue;
    47             if(board[tx][ty]!=word[p])
    48                 continue;
    49             mark[tx][ty]=true;
    50             if(deep(board,mark,p+1,word,tx,ty))
    51                 return true;
    52             mark[tx][ty]=false;
    53         }
    54         return false;
    55     }
    56 };
    View Code
  • 相关阅读:
    编程范式 epesode7,8 stack存放指针类型and heap,register
    编程范式 episode 6 实现stack 栈功能_ to do
    C 运算符优先级
    编程范式 episode3 and 4,5
    编程范式 epesode2 negative values, float 精度
    C 数据类型 长度
    memcpy code
    排序算法 2 qsort 库函数,泛型函数
    sin, miss the mark, correct our aim and try again
    排序算法 1
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105962.html
Copyright © 2011-2022 走看看