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

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

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.

class Solution {public:bool dfs(string word, int row, int col){    if(word.size() == 0) return true;    if(col < 0 || col >= n || row < 0 || row >= m || board[row][col] != word[0]) return false;     bool b1, b2, b3, b4;     board[row][col] = '#';     b1 = dfs(word.substr(1, word.size() - 1),row + 1, col);     if(b1) return true;     b2 = dfs(word.substr(1, word.size() - 1), row, col + 1);     if(b2) return true;     b3 = dfs(word.substr(1, word.size() - 1), row - 1, col);     if(b3) return true;     b4 = dfs(word.substr(1, word.size() - 1), row, col - 1);     if(b4) return true;     board[row][col] = word[0];     return false;}    bool exist(vector
> &board, string word) { this->board = board; m = board.size(); if(m <= 0) return false; n = board[0].size(); if(word.size() == 0) return true; bool re = false; for(int i = 0; i < m; ++i) for(int j = 0; j < n; ++j) { re = dfs(word,i,j); if(re == true) return true; } return re; } private: vector
> board; int m, n;};
跪了,300ms左右。。。要尝试bfs来弄下,看看如何。

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

你可能感兴趣的文章
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Sum Root to leaf Numbers
查看>>
【leetcode】Pascal's Triangle II (python)
查看>>
java自定义容器排序的两种方法
查看>>
如何成为编程高手
查看>>
本科生的编程水平到底有多高
查看>>
使用与或运算完成两个整数的相加
查看>>
备忘:java中的递归
查看>>
Solr及Spring-Data-Solr入门学习
查看>>
python_time模块
查看>>
python_configparser(解析ini)
查看>>
selenium学习资料
查看>>
<转>文档视图指针互获
查看>>