leetcode 079 —— Word Search
来源:互联网 发布:js关闭当前页面并跳转 编辑:程序博客网 时间:2024/05/16 10:38
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 =
[ ["ABCE"], ["SFCS"], ["ADEE"]]word =
"ABCCED"
, -> returns true
,word =
"SEE"
, -> returns true
,word =
"ABCB"
, -> returns false
.思路: 思路,用一个矩阵记录被使用的单词,但是代码跑了44ms,还有优化的空间
class Solution {public:bool exist(vector<vector<char>>& board, string word) {bool judge = false;int level = 0;vector<vector<bool>> record(board.size(), vector<bool>(board[0].size(), false));for (int m = 0; m <board.size(); m++){for (int n = 0; n <board[0].size(); n++){if (board[m][n] == word[0]){record[m][n] = true;level = 1;scan(m, n, judge, level, word, record, board);if (judge) return judge;record[m][n] = false;}}}return judge;}void scan(int i, int j, bool &judge,int &level, string &word,vector<vector<bool>> &record,vector<vector<char>> &board){if (level== word.size()){judge = true;return;}if (i + 1 < board.size() && !record[i + 1][j] && board[i + 1][j] == word[level]){ //往右 record[i + 1][j] = true;level++;scan(i + 1, j, judge, level, word, record, board);level--;if (judge) return;record[i + 1][j] = false;}if (i - 1 >= 0 && !record[i - 1][j] && board[i - 1][j] == word[level]){//往左record[i - 1][j] = true;level++;scan(i - 1, j, judge, level, word, record, board);level--;if (judge) return;record[i - 1][j] = false;}if (j + 1 < board[0].size() && !record[i][j + 1] && board[i][j+1] == word[level]){//往下record[i][j+1] = true;level++;scan(i, j + 1, judge, level, word, record, board);level--;if (judge) return;record[i][j+1] = false;}if (j - 1 >= 0 && !record[i][j - 1] && board[i][j-1] == word[level]){//往上record[i][j-1] = true;level++;scan(i , j-1, judge, level, word, record, board);if (judge) return;level--;record[i][j-1] = false;}}};
0 0
- [LeetCode]—Word Search
- leetcode 079 —— Word Search
- LeetCode —— Word Search
- leetcode——Word Search
- LeetCode: Word Search [079]
- 079 Word Search[Leetcode]
- LeetCode 079 Word Search
- leetcode 079 word search
- 【leetcode】Array——word search(79)
- LeetCode——79. Word Search
- LeetCode—212 Word Search II
- leetcode——79—— Word Search
- leetcode——Add and Search Word - Data structure design
- LeetCode刷题(C++)——Word Search(Medium)
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- 1. HTML DOM Document 对象
- hdu 1520 Anniversary party 树形DP
- CKEditor文字编辑器
- linux 信号列表
- oprofile抓不到采样数据问题和解决方法
- leetcode 079 —— Word Search
- 南邮 OJ 1005 多项式加法
- shell中各种括号的作用()、(())、[]、[[]]、{}
- 【转】java程序访问derby的两种模式实例
- 社説 20150803 戦争遺跡 悲惨な記憶を後世に伝えよう
- slf4j和logback的详细使用(二)
- hdu 4135 Co-prime(容斥原理)
- svn 删除服务器和本地的文件
- Linux - EXT2文件系统