博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Word Search
阅读量:4151 次
发布时间:2019-05-25

本文共 2558 字,大约阅读时间需要 8 分钟。

int Dir[4][2]={
{0,1},{0,-1},{1,0},{-1,0}};class Solution {//DFS Find the pathpublic: void DFS(int curX, int curY, int curPos, vector
>& visit, bool& OK, vector
> &board, string& word ) { if(OK) return; if(word[curPos] != board[curX][curY]) return; if(curPos == word.size()-1) { OK = true; return; } for (int d = 0; d < 4; ++d) { int nextX = curX+Dir[d][0]; int nextY = curY+Dir[d][1]; if(nextX >= 0 && nextX < board.size() && nextY >= 0 && nextY < board[0].size()) { if(!visit[nextX][nextY]) { visit[nextX][nextY] = true; DFS(nextX, nextY, curPos+1, visit, OK, board, word); visit[nextX][nextY] = false; } } } }public: bool exist(vector
> &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function if(word.size() == 0) return false; if(board.size() == 0 || board[0].size() == 0) return false; bool OK = false; vector
> visit(board.size(), vector
(board[0].size(), false)); for (int i = 0; i < board.size(); ++i) { for (int j = 0; j < board[i].size(); ++j) { visit[i][j] = true; DFS(i, j, 0, visit, OK, board, word); visit[i][j] = false; if(OK) return true; } } return false; }};

second time

class Solution {public:    int dir[4][2] = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; bool findPath(vector
> &board, string& word, vector
>& used, int curX, int curY, int curIdx) { int n = board.size(); int m = board[curX].size(); if(curIdx == word.size()) return true; for(int k = 0; k < 4; ++k) { int newX = curX+dir[k][0]; int newY = curY+dir[k][1]; if(newX >= 0 && newX < n && newY >= 0 && newY < m && used[newX][newY] == false && board[newX][newY] == word[curIdx]) { used[newX][newY] = true; if(findPath(board, word, used, newX, newY, curIdx+1)) return true; used[newX][newY] = false; } } return false; } bool exist(vector
> &board, string word) { // Start typing your C/C++ solution below // DO NOT write int main() function if(word.size() == 0) return true; int n = board.size(); if(n == 0) return false; int m = board[0].size(); vector
> used(n, vector
(n, false)); for(int i = 0; i < board.size(); ++i) { for(int j = 0; j < board[i].size(); ++j) { if(board[i][j] == word[0]) { used[i][j] = true; if(findPath(board, word, used, i, j, 1)) return true; used[i][j] = false; } } } return false; }};

转载地址:http://mhxti.baihongyu.com/

你可能感兴趣的文章
码农:和产品对一天需求,产品经理的需求是对完了,可我代码呢?
查看>>
程序员过年回家该怎么给亲戚朋友解释自己的职业?
查看>>
技术架构师的日常工作是什么?网友:搭框架,写公共方法?
查看>>
第四章 微信飞机大战
查看>>
九度:题目1008:最短路径问题
查看>>
九度Online Judge
查看>>
九度:题目1027:欧拉回路
查看>>
九度:题目1012:畅通工程
查看>>
九度:题目1017:还是畅通工程
查看>>
九度:题目1034:寻找大富翁
查看>>
第六章 背包问题——01背包
查看>>
51nod 分类
查看>>
1136 . 欧拉函数
查看>>
面试题:强制类型转换
查看>>
Decorator模式
查看>>
Template模式
查看>>
Observer模式
查看>>
高性能服务器设计
查看>>
性能扩展问题要趁早
查看>>
MySQL-数据库、数据表结构操作(SQL)
查看>>