LeetCode: 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

可以通过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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值