leetcode Word Search
来源:互联网 发布:淘宝的支付方式 编辑:程序博客网 时间:2024/06/14 00:26
我的第一次代码 85/87 那aaaaa的数据没过 哎难受 后面一点点的看 优化了一下 然后 勉强ac
class Solution {
public:
vector<pair<int, int>> walk{{1,0},{-1,0},{0,1},{0,-1}};
bool isExist(vector<vector<char>> board,string word,vector<vector<bool>> &used,int x,int y,int l)
{ // x,y为末尾已经的到达坐标
if(l>word.size()-1||word.size()==0)
return true;
bool flag=false;
bool bb[4]={false};
for(int i=0;i<=walk.size()-1;i++)
{
int newx=x+walk[i].first;
int newy=y+walk[i].second;
if(newx>=0&&newx<=board.size()-1&&newy>=0&&newy<=board[0].size()-1&&board[newx][newy]==word[l]&&used[newx][newy]==0)
{
flag=true;
used[newx][newy]=1;
bb[i]=isExist(board, word, used, newx, newy,l+1);
used[newx][newy]=0;
if(bb[i]==true) //加了这两行就ac ,没加就超时,以后还是要好好优化 能省时间则省
return bb[i];
}
}
return bb[0]||bb[1]||bb[2]||bb[3];
}
bool exist(vector<vector<char>>& board, string word) {
vector<vector<bool>> used;
vector<bool> b;
for(int i=0;i<=board[0].size()-1;i++)
b.push_back(false);
for(int i=0;i<=board.size()-1;i++)
used.push_back(b);
string newone=word.substr(1);
for(int i=0;i<=board.size()-1;i++)
for(int j=0;j<=board[0].size()-1;j++)
if(board[i][j]==word[0])
{
used[i][j]=1;
if(isExist(board, newone, used, i, j,0))
return true;
used[i][j]=0;
}
return false;
}
};
这是discuss上的一个老哥的解法:标题是my 19ms c++ 解法
我贴过来一下 纪录以后再看
https://leetcode.com/problems/word-search/discuss/
classSolution {public:boolexist(vector<vector<char> > &board, string word){ m=board.size(); n=board[0].size();for(int x=0;x<m;x++)for(int y=0;y<n;y++) { if(isFound(board,word.c_str(),x,y))returntrue; } returnfalse; } private:int m; int n; boolisFound(vector<vector<char> > &board, const char* w, int x,int y) {if(x<0||y<0||x>=m||y>=n||board[x][y]=='\0'||*w!=board[x][y])returnfalse;if(*(w+1)=='\0')returntrue;char t=board[x][y]; board[x][y]='\0';if(isFound(board,w+1,x-1,y)||isFound(board,w+1,x+1,y)||isFound(board,w+1,x,y-1)||isFound(board,w+1,x,y+1))returntrue; board[x][y]=t; returnfalse; } };
- LeetCode: Word Search
- [Leetcode] Word Search
- LeetCode : Word Search
- Leetcode: Word Search
- [LeetCode] Word Search
- leetcode 56: Word Search
- Leetcode 79 Word Search
- [leetcode ] word search
- [Leetcode] Word Search
- [LeetCode]Word Search
- Leetcode Word Search
- [leetcode]word search
- [leetcode] Word Search
- LeetCode-Word Search
- [LeetCode] Word Search
- LeetCode - Word Search
- leetcode word search
- LeetCode:Word Search
- MyBatis入门
- 博客已搬家
- 【HDU
- ios-换肤简单实现
- PopupWindow设置背景
- leetcode Word Search
- 修改Gradle 和Maven本地仓库的位置 方法
- POJ 2259(用空间换取时间)
- 为什么内存映射要比IO读写更加快速
- 2017.11.01前端小记
- ZOJ 3983 && 2017CCPC秦皇岛 C:Crusaders Quest
- LeetCode基础-排序-快速排序
- 微信小程序布局(一)
- linux ssh 不保存操作记录history