Leetcode79

本文介绍了一个二维网格中查找单词的算法。通过递归回溯,从每个可能的起点出发,检查给定单词是否能由相邻的字符组成。该算法详细解释了如何避免重复使用同一字符,并提供了完整的C++实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
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.

Solution:

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

class Solution {
private:
     int d[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
     int m, n;
     vector<vector<bool>> visited;

     bool inArea(int x, int y){
         return x >= 0 && x < m && y >= 0 && y < n;
     }

     // 从board[startx][starty]开始,寻找word[index...word.size()]
     bool searchWord(const vector<vector<char>> &board, const string& word, int index,
                     int startx, int starty){
         if ( index == word.size() - 1)
             return board[startx][starty] == word[index];

         if ( board[startx][starty] == word[index] ){
             visited[startx][starty] = true;
             // 从startx, starty出发,向四个方向寻找
             for(int i = 0; i < 4; i++){
                 // 小技巧,这个cell的四个方向
                 int newx = startx + d[i][0];
                 int newy = starty + d[i][1];
                 if( inArea(newx,newy) && !visited[newx][newy] &&
                         searchWord( board, word, index + 1, newx, newy))
                     return true;
             }
             visited[startx][starty] = false;
         }

         return false;
     }
public:
    bool exist(vector<vector<char>>& board, string word) {

        m = board.size();
        assert( m > 0);
        n = board[0].size();

        visited = vector<vector<bool>>(m, vector<bool>(n, false));

        for (int i = 0; i < board.size() ; i++) {
            for (int j = 0; j < board[i].size() ; j++) {
                if (searchWord(board, word, 0, i, j))
                    return true;
            }
        }

        return false;
    }
};

总结: 二维平面上的回溯问题,值得回味!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值