LeetCode
来源:互联网 发布:温度数据采集板 编辑:程序博客网 时间:2024/04/19 20:42
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
.在一个board是否能找到某个单词,单词中相邻字母需要在格子中相邻(用过的字母不可再用)。
一个dfs,时间复杂度O(nm),空间复杂度O(nm)
class Solution {private: int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1};public: bool exist(vector<vector<char>>& board, string word) { if (word.size() == 0) return true; if (!board.size() || !board[0].size()) return false; int n = board.size(), m = board[0].size(); bool ans = false; vector<vector<bool> > vis(n, vector<bool>(m, false)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (board[i][j] == word[0]) { vis[i][j] = true; dfs(board, vis, word, i, j, 0, ans); vis[i][j] = false; if (ans) return true; } } } return false; } void dfs(vector<vector<char> >& board, vector<vector<bool> >& vis, string word, int x, int y, int loc, bool& ans) { if (ans) return; if (board[x][y] != word[loc]) return; if (loc == word.length() - 1) { ans = true; return; } for (int i = 0; i < 4; ++i) { int xx = x + dir[i][0]; int yy = y + dir[i][1]; if (xx < 0 || yy < 0 || xx >= board.size() || yy >= board[0].size()) continue; if (vis[xx][yy]) continue; vis[xx][yy] = true; dfs(board, vis, word, xx, yy, loc+1, ans); vis[xx][yy] = false; } }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- HDU-1874 畅通工程续
- I
- 剑指offer-10:二进制中1的个数
- PHPcms V9 的目录结构
- POJ 2777 线段树
- LeetCode
- Poj—2431 Expedition 优先队列使用经典例题
- 基于STM8S003的无源蜂鸣器播放音乐
- Sublime Text3通过HTML-CSS-JS Prettify自动格式化代码
- linux 链接jsoncpp库时候, 编译出错问题
- LeetCode-Easy-Java-Longest Common Prefix
- Halcon实现边缘提取
- 通过注解方式配置Spring实现Ioc
- [排序] 冒泡排序(Python)