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

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

题目连接

  

Word Search

Description

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.

const int dx[] = { 0, 0, -1, 1 }, dy[] = { -1, 1, 0, 0 };class Solution {public:	int n, H, W;	bool exist(vector
>& board, string word) { n = word.length(); H = board.size(), W = board[0].size(); queue
>q; for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { if (word[0] == board[i][j]) { vector
> vis(H, vector
(W)); vis[i][j] = true; if (dfs(i, j, vis, board, word, 1)) return true; } } } return false; } bool dfs(int x, int y, vector
>& vis, vector
>& board, string word, int cur) { if (cur == n) return true; for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= H || ny <0 || ny >= W) continue; if (board[nx][ny] == word[cur] && !vis[nx][ny]) { vis[nx][ny] = true; if (dfs(nx, ny, vis, board, word, cur + 1)) return true; vis[nx][ny] = false; } } return false; }};

转载于:https://www.cnblogs.com/GadyPu/p/5034149.html

你可能感兴趣的文章
网页内容抓取
查看>>
分布式和集群的区别
查看>>
Python基础(三)
查看>>
Sql server在cmd下的使用
查看>>
【BZOJ 1019】 1019: [SHOI2008]汉诺塔 (DP?)
查看>>
swing
查看>>
Continuous integration
查看>>
前端知识点总结
查看>>
github 在ubuntu 使用--常用命令
查看>>
hl7 V2中Message Control ID的含义及应用
查看>>
IOS 4个容易混淆的属性(textAligment contentVerticalAlignment contentHorizontalAlignment contentMode)...
查看>>
iOS 修改textholder的颜色
查看>>
【资料】wod地城掉落
查看>>
C# FTPHelper(搬运)
查看>>
C#HttpHelper类1.3正式版教程与升级报告
查看>>
【转】Android 语言切换过程分析
查看>>
jpa 多对多关系的实现注解形式
查看>>
Android开发——View绘制过程源码解析(一)
查看>>
Quartz和TopShelf Windows服务作业调度
查看>>
让ie9之前的版本支持canvas
查看>>