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.

    分析: 刚开始做的时候有误解,实际上就是从矩阵中找一条线路求解出word dfs求解最方便,注意一下边界范围

    class Solution {
    private: 
        int rows;
        int cols;
    public:
        bool exist(vector<vector<char>>& board, string word) {
            rows = board.size();
            cols = board[0].size();
            for(int i=0; i< rows; i++)
                for(int j=0;j<cols; j++){
                    if(dfs(board,i,j,word,0))
                        return true;
                }
            return false;
        }
        bool dfs(vector<vector<char>>& board, int x, int y,string word, int index){
            //cout << x << " "<<y <<endl;
            //cout << "index = "<<index<<endl;
            if(x<0 || y<0 || x>=rows || y>=cols || (index<word.size() && board[x][y]!=word[index])  )
                return false;
            if(index+1 == word.size()){
                 return true;
            }
            char c =board[x][y];
            board[x][y] = '.';
            if(dfs(board,x-1,y,word,index+1) || dfs(board,x+1,y,word,index+1)
               || dfs(board,x,y-1,word,index+1) || dfs(board,x,y+1,word,index+1))
                   return true;
             
            board[x][y] =c;
          
            return false;
        }
    };

      

  • 相关阅读:
    Goldbach's Conjecture
    查找素数
    最大公约数和最小公倍数
    迭代求立方根
    计算两个矩阵的乘积
    随机选择算法
    有几个PAT
    python3学习笔记之安装
    Ubuntu 16.04卸载一些不必要的预装软件
    Xshell连接不上虚拟机提示ssh服务器拒绝了密码,请再试一次
  • 原文地址:https://www.cnblogs.com/willwu/p/6250266.html
Copyright © 2011-2022 走看看