LeetCode: Word Search

来源:互联网 发布:c语言less 编辑:程序博客网 时间:2024/06/05 08:20

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

可以通过leetcode平台测试。以下是在visual studio 2015上的测试
思路:

  1. 遍历整个board
  2. 搜索到第一个匹配字符
  3. 搜索当前字符位置的上下左右位置的字符是否匹配并且把上一次搜索到的字符设置为无效字符即’\0’
  4. 把原位置字符还原
  5. 注意判断循环的退出条件
// WordSearch.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "iostream"#include "vector"#include "string"using namespace std;class Solution {public:    bool exist(vector<vector<char> >&board, string word) {        int row = board.size();        int col = board[0].size();        for (int i = 0; i < row; i++)            for (int j = 0; j < col; j++)            {                if (findCurrAndNext(board, word, i, j, row, col))                {                    return true;                }            }        return false;    }    bool findCurrAndNext(vector<vector<char> >& board, string word, int i, int j,int row,int col);};//i j: the location of current search bool Solution::findCurrAndNext(vector<vector<char> >& board, string word, int i, int j,int row, int col){    const char* str=word.c_str();//type is const     //the current search location whether Yes    if (i < 0 || j < 0 || i >= row || j >= col || board[i][j] == '\0' || *str != board[i][j])    {        return false;    }    //end of word search    if (*(str + 1) == '\0')    {        return true;    }    //The location of the last search was set to an invalid location    char c = board[i][j];    board[i][j] = '\0';    //search up,down,left,right of the current location    if (findCurrAndNext(board, str + 1, i - 1, j, row, col) || findCurrAndNext(board, str + 1, i + 1, j, row, col)\        || findCurrAndNext(board, str + 1, i, j - 1, row, col) || findCurrAndNext(board, str + 1, i, j + 1, row, col))    {        return true;    }    //change the last character to the original character    board[i][j] = c;    return false;}int main(){    string str = "nihao";    const char* c = str.c_str();    cout << *c << endl;    system("pause");    return 0;}
原创粉丝点击