leetcode_89 Word Search

161 篇文章 0 订阅

题目:

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.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

Constraints:

  • board and word consists only of lowercase and uppercase English letters.
  • 1 <= board.length <= 200
  • 1 <= board[i].length <= 200
  • 1 <= word.length <= 10^3

首先遍历找到第一个元素,然后进行深度优先遍历。需要注意的是dfs有返回值,那么每次递归调用都要处理返回值,要return

其次,由于匹配的前一个字母也在相邻的位置,而又不能再匹配,因此,要对已经匹配的位置进行标记。如果后面的匹配失败,前面已经标记的也要回溯的时候重新置位false,这个点还真有点绕。字符串“ABCB”就是这种情况。

class Solution {
public:
    int dx[4] = {0,0,1,-1};
    int dy[4] = {1,-1,0,0};
    int Row,Col;
    bool visited[200][200];
    bool dfsBoard(vector<vector<char> > &board,int i,int j,string word,int cnt)
    {
        if(cnt >= word.length())
        {
            if(cnt == word.length())
                return true;
            else
                return false;
        }
        for(int k = 0; k < 4; k++)
        {
            int nx = i + dx[k];
            int ny = j + dy[k];
            if(nx >= 0 && nx < Row && ny >= 0 && ny < Col)
            {
                if(board[nx][ny] == word[cnt] && !visited[nx][ny])
                {
                    visited[nx][ny] = true;
                    if(dfsBoard(board,nx,ny,word,cnt + 1))
                        return true;
                    visited[nx][ny] = false;
                }
            }
        }
        return false;
    }
    bool exist(vector<vector<char>>& board, string word) {
        int len = word.length();
        if(len == 0)  return true;
        int m = board.size();
        if(m == 0)  return false;
        int n = board[0].size();
        if(n == 0)  return false;
        Row = m, Col = n;
        memset(visited,false,200*200);
        for(int i = 0; i < m; i++)
        {
            for(int j = 0; j < n; j++)
            {
                if(board[i][j] == word[0] && !visited[i][j])
                {   
                    visited[i][j] = true;
                    if(true == dfsBoard(board,i,j,word,1))
                        return true;
                    visited[i][j] = false;
                }
            }
        }
        return false;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值