zoukankan      html  css  js  c++  java
  • 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 #include <vector>
     2 #include <string>
     3 #include <algorithm>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Solution {
     8 public:
     9     bool exist(vector<vector<char>>& board, string word) {
    10         int m = board.size();
    11         int n = board[0].size();
    12         
    13         vector<vector<bool>> visited(m,vector<bool>(n,false));
    14         for(int i=0;i<m;i++){
    15             for(int j=0;j<n;j++){
    16                 if(board[i][j] == word[0]){
    17                     if(dfs(i,j,0,board,word,visited))
    18                         return true;
    19                 }
    20             }
    21         }
    22         return false;
    23     }
    24 
    25     bool dfs(int x,int y,int curr,vector<vector<char>>& board,
    26         string& word,vector<vector<bool>>& visited){
    27 
    28         int m = board.size();
    29         int n = board[0].size();
    30 
    31         if(curr == word.size())  return true;
    32 
    33         if(x<0 || x>=m || y<0 || y>=n) return false;
    34 
    35         if(board[x][y] != word[curr])  return false;
    36 
    37         if(visited[x][y] == true) return false;
    38 
    39         visited[x][y] = true;
    40         bool ret= dfs(x, y+1, curr+1, board, word,visited) ||
    41                dfs(x+1, y, curr+1, board, word,visited) ||
    42                dfs(x, y-1, curr+1, board, word,visited) ||
    43                dfs(x-1, y, curr+1, board, word,visited);
    44         visited[x][y] = false;
    45         return ret;
    46     }
    47 };
    48 
    49 int main()
    50 {
    51 
    52     vector<vector<char>> board{{'a','a'}};
    53     Solution s;
    54     cout << s.exist(board, "aaa") << endl;
    55     return 0;
    56 
    57 }
  • 相关阅读:
    数据库连接代码
    智能家居资源汇总
    android应用设计与实现相关资源汇总
    嵌入式设计应用资料汇总,不定时更新中……
    Zigbee相关资料大全,不断更新中……
    H.264视频编码资料汇总,不断更新……
    星网锐捷笔试
    华为 10第二题 成都 约瑟夫环
    2014华为校园招聘上机测试题目(华科提前批)
    2014年华为校招成渝地区上机试题
  • 原文地址:https://www.cnblogs.com/wxquare/p/5011538.html
Copyright © 2011-2022 走看看