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

方法1: dfs

思路:

首先遍历一遍找到词首字母,开始对上下左右dfs,寻找下一个字符。注意找到match 字符的位置需要被标记为visited,因为题目说同一位置的字符不能被用两次。

易错点

  1. 退出条件
  2. visited要用backtracking里的方式在退出之后恢复成false,给别的dfs机会再利用这个未知的字符。

Complexity

Time complexity: ?(?∗?∗4^ ?), where s is the length of the string, mn for for loop and for the dfs method its 4^ s. Since the dfs method goes only as deep as the word length we have T(k)=4(T(k-1))=4*4T(k-2)=…=… which will be 4^k.

Space complexity: O(mn), for visited matrix, 但是也有可能用一个特殊符号在原位标记visited,这样可以达到O(1)。space O(4mn) if the function call stack is taken into account. In each cell, we recursively call its 4four neighbors and there are mn cells in total.

class Solution {
public:
    bool exist(vector<vector<char>>& board, string word) {
        if (board.empty() || board[0].empty()) return false;
        int m = board.size();
        int n = board[0].size();
        vector<vector<bool>> visited(m, vector<bool> (n, false));
        for (int i = 0 ; i < board.size(); i++){
            for (int j = 0; j < board[0].size(); j++){ 
                if (dfs(board, word, 0, visited, i, j)) return true;
            }
        }
        return false;
    }
    
    bool dfs(vector<vector<char>> & board, string word, int start, vector<vector<bool>> & visited, int x, int y){
        if (start == word.size()) return true;
        if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || visited[x][y] || board[x][y] != word[start] ) return false;
        
        visited[x][y] = true;
        bool ret = dfs(board, word, start + 1, visited, x + 1, y)
                || dfs(board, word, start + 1, visited, x - 1, y)
                || dfs(board, word, start + 1, visited, x, y + 1)
                || dfs(board, word, start + 1, visited, x, y - 1);
        visited[x][y] = false;
        
        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这段代码存在一些问题: 1. EnglishLearningApp 类没有定义完整,缺少 quiz_page 函数实现。 2. 在 word_consult 函数中,创建了一个名为 word_entry 的 Entry 对象,但是它没有被放置到任何容器中,应该使用 self.word_entry。 3. 在 add_word 函数中,使用了 search_entry.get(),但是没有定义 search_entry 对象,应该使用 self.word_entry.get()。 4. 在 add_word 函数中,使用了 cur.execute(),但是应该使用 self.cursor.execute()。 5. 在 add_word 函数中,应该把获取的 word 对象转换为字符串,即使用 word[0]。 6. 在 add_word 函数中,应该加入 try-except 结构,以处理插入或删除单词时可能发生的异常情况。 下面是修改后的代码: ``` import tkinter as tk import sqlite3 import random from tkinter import messagebox class EnglishLearningApp: def __init__(self, master): self.master = master master.title("英语学习软件") self.database_button = tk.Button(master, text="单词库", command=self.word_consult) self.database_button.pack(pady=10) self.quiz_button = tk.Button(master, text="英语默写", command=self.quiz_page) self.quiz_button.pack(pady=10) self.conn = sqlite3.connect('words.db') self.cursor = self.conn.cursor() self.cursor.execute('''CREATE TABLE IF NOT EXISTS words (word text PRIMARY KEY)''') self.conn.commit() def word_consult(self): self.word_entry = tk.Entry(self.master) self.word_entry.pack(padx=10, pady=10) self.add_button = tk.Button(self.master, text="添加/删除单词", command=self.add_word) self.add_button.pack(pady=5) def add_word(self): word = self.word_entry.get() if not word: return try: self.cursor.execute("SELECT * FROM data WHERE name=?", (word,)) word = self.cursor.fetchone() if word: self.cursor.execute("INSERT INTO words VALUES (?)", (str(word[0]),)) self.conn.commit() messagebox.showinfo("提示", "添加成功") else: self.cursor.execute("DELETE FROM words WHERE word=?", (word[0],)) self.conn.commit() messagebox.showinfo("提示", "删除成功") except Exception as e: messagebox.showerror("错误", str(e)) def quiz_page(self): pass if __name__ == '__main__': root = tk.Tk() app = EnglishLearningApp(root) root.mainloop() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值