当前位置:网站首页>Leetcode79 method 1: deep search
Leetcode79 method 1: deep search
2022-07-28 18:23:00 【L Qi Tian】
- Word search
Given a two-dimensional grid and a word , Find out if the word exists in the grid .
The words must be in alphabetical order , It's made up of letters in adjacent cells , among “ adjacent ” Cells are those adjacent horizontally or vertically . Letters in the same cell are not allowed to be reused .
Example :
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
Given word = “ABCCED”, return true
Given word = “SEE”, return true
Given word = “ABCB”, return false
Tips :
board and word Contains only uppercase and lowercase letters .
1 <= board.length <= 200
1 <= board[i].length <= 200
1 <= word.length <= 10^3
Execution time : 184 ms
Memory consumption : 120.8 MB
class Solution {
public:
bool check(vector<vector<char>>& board, vector<vector<int>>& visited, string word, int i, int j, int k, int h, int w) {
//i j Is the coordinate of the current point k Is used to mark which character needs to be queried
/* Two logics If this element is not, then go back If it has been found, exit */
if (board[i][j] != word[k]) {
return false;
}
else if (k == word.length() - 1) {
return true;
}
// Set up visited
visited[i][j] = 1;
// Found this element but didn't end
k += 1;// If you find this element, you can self increase
int temp_i;
int temp_j;
// Set offset
vector<pair<int, int>>direction{
{
0, 1},{
0 ,-1},{
1, 0},{
-1, 0} };// Right Left On Next
for (int n = 0; n < 4; n++) {
temp_i = i + direction[n].first;
temp_j = j + direction[n].second;
if (temp_i == h || temp_j == w || temp_i == -1 || temp_j == -1)continue;
if (!visited[temp_i][temp_j]) {
//cout << "(" << temp_i + 1 << "," << temp_j + 1 << ")" << endl;
if (check(board, visited, word, temp_i, temp_j, k, h, w))return true;
}
}
// After four cycles, it is found that no usable element can be found Restore it to 0 That's important
visited[i][j] = 0;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int i, j, k;
int h = board.size(), w = board[0].size();
// Get the position of the first letter Determine the starting point
char star = word[0];// Get the first letter
vector<int>coordinate;// Store coordinates
// The coordinates were successfully stored in coordinate in
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
if (board[i][j] == star) {
coordinate.push_back(i);
coordinate.push_back(j);
}
}
}
// Initialize a check matrix The checked element is set to 1
vector<vector<int>> visited(h, vector<int>(w, 0));
//DFS start-up
bool flag;
for (k = 0; k < coordinate.size() / 2; k++) {
flag = check(board, visited, word, coordinate[k * 2], coordinate[k * 2 + 1], 0, h, w);
if (flag) return true;
// hold visited All set to 0
vector<vector<int>> visited(h, vector<int>(w, 0));
}
return false;
}
};
Appropriate optimization :
Don't open up too many new visited Repeated use
Yes word Array adopts reference
Execution time : 76 ms
Memory consumption : 17 MB
class Solution {
public:
bool check(vector<vector<char>>& board, vector<vector<int>>& visited, string& word, int i, int j, int k, int h, int w) {
//i j Is the coordinate of the current point k Is used to mark which character needs to be queried
/* Two logics If this element is not, then go back If it has been found, exit */
//cout << "(" << i+1 << "," << j+1 << ")" << endl;
bool result = false;
if (board[i][j] != word[k]) {
return false;
}
else if (k == word.length() - 1) {
return true;
}
// Set up visited
visited[i][j] = 1;
// Found this element but didn't end
k += 1;// If you find this element, you can self increase
int temp_i;
int temp_j;
// Set offset
vector<pair<int, int>>direction{
{
0, 1},{
0 ,-1},{
1, 0},{
-1, 0} };// Right Left On Next
for (int n = 0; n < 4; n++) {
temp_i = i + direction[n].first;
temp_j = j + direction[n].second;
if (temp_i == h || temp_j == w || temp_i == -1 || temp_j == -1)continue;
if (!visited[temp_i][temp_j]) {
if (check(board, visited, word, temp_i, temp_j, k, h, w)) {
result = true;
break;
}
}
}
// After four cycles, it is found that no usable element can be found Restore it to 0
visited[i][j] = 0;
return result;
}
bool exist(vector<vector<char>>& board, string word) {
int i, j, k;
int h = board.size(), w = board[0].size();
// Get the position of the first letter Determine the starting point
char star = word[0];// Get the first letter
vector<int>coordinate;// Store coordinates
// The coordinates were successfully stored in coordinate in
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
if (board[i][j] == star) {
coordinate.push_back(i);
coordinate.push_back(j);
}
}
}
// Initialize a check matrix The checked element is set to 1
vector<vector<int>> visited(h, vector<int>(w, 0));
//DFS
bool flag;
for (k = 0; k < coordinate.size() / 2; k++) {
flag = check(board, visited, word, coordinate[k * 2], coordinate[k * 2 + 1], 0, h, w);
if (flag) return true;
// hold visited All set to 0
}
return false;
}
};
Optimize... Again :
add to private To store some data and speed up the operation
Execution time :24 ms, In all C++ Defeated in submission 93.89% Users of
Memory consumption :8.8 MB, In all C++ Defeated in submission 44.96% Users of
class Solution {
private:
vector<pair<int, int>>direction{
{
0, 1},{
0 ,-1},{
1, 0},{
-1, 0} };// Right Left On Next
public:
bool check(vector<vector<char>>& board, vector<vector<int>>& visited, string& word, int i, int j, int k, int h, int w) {
//i j Is the coordinate of the current point k Is used to mark which character needs to be queried
/* Two logics If this element is not, then go back If it has been found, exit */
bool result = false;
if (board[i][j] != word[k]) {
return false;
}
else if (k == word.length() - 1) {
return true;
}
// Set up visited
visited[i][j] = 1;
// Found this element but didn't end
k += 1;// If you find this element, you can self increase
int temp_i;
int temp_j;
// Set offset
for (int n = 0; n < 4; n++) {
temp_i = i + direction[n].first;
temp_j = j + direction[n].second;
if (temp_i == h || temp_j == w || temp_i == -1 || temp_j == -1)continue;
if (!visited[temp_i][temp_j]) {
if (check(board, visited, word, temp_i, temp_j, k, h, w)) {
result = true;
break;
}
}
}
// After four cycles, it is found that no usable element can be found Restore it to 0
visited[i][j] = 0;
return result;
}
bool exist(vector<vector<char>>& board, string word) {
int i, j, k;
int h = board.size(), w = board[0].size();
// Get the position of the first letter Determine the starting point
char star = word[0];// Get the first letter
vector<int>coordinate;// Store coordinates
// The coordinates were successfully stored in coordinate in
for (i = 0; i < h; i++) {
for (j = 0; j < w; j++) {
if (board[i][j] == star) {
coordinate.push_back(i);
coordinate.push_back(j);
}
}
}
// Initialize a check matrix The checked element is set to 1
vector<vector<int>> visited(h, vector<int>(w, 0));
//DFS
bool flag;
for (k = 0; k < coordinate.size() / 2; k++) {
flag = check(board, visited, word, coordinate[k * 2], coordinate[k * 2 + 1], 0, h, w);
if (flag) return true;
// hold visited All set to 0
}
return false;
}
};
边栏推荐
- MySQL operation Encyclopedia
- 频谱仪原理简介一
- Summary of core knowledge points of Computer Composition Principles & key points of written interview [easy to understand]
- 体验5分钟开发微信小程序
- 七个步骤,深入解读数据含义
- vmware虚拟机联网设置(win10自带虚拟机安装win7)
- Digital filter (III) -- Design of analog filter
- Five key considerations for network security budget planning in 2023
- TCP/IP详细图解
- Andorid: Zxing.Demo二维码扫描框架遇到的坑
猜你喜欢

Seven steps, in-depth interpretation of data meaning

矢量网络分析仪(矢网)的校准

DC-DC开关电源

Tips -- solve the problem of no module named matlab.engine

示波器简介

Openmv (III) -- get camera pictures in real time

Power adapter global definition

WordPress prompt error in establishing database connection

Openmv (V) -- STM32 to realize face recognition

The growth path of hardware engineers (0) -- Understanding components
随机推荐
After CentOS uses docker to run mysql, the remote connection needs to open the port
初识结构体
VSC上写Go出现expected ‘package‘, found ‘EOF‘
高温天气户外活动有讲究!市民盛夏健身安全指引来了
矢量网络分析仪(矢网)组成和原理简介
Advanced Design System(ADS)2009 射频仿真入门
示波器探头详解
Iptables firewall port rule configuration
Live video Number supports product playback
10.8亿美元!TCL科技收购三星苏州8.5代线:未来一年产能将增长60%!
This tool is enough for video number operation
天线的主要参数介绍
华为中兴在英国败诉,不交专利授权费将被禁售!
What is the future prospect of video Number e-commerce?
Through private channels such as official account, direct the live broadcast of video number
USB Type-C 详解
Centos8 creates wordpress+mysql error reports according to the official website of docker
MediaTek has submitted an application to the US side, striving to supply goods to China after September 15
Tips -- understanding of the physical meaning of convolution
Functions brought by the binding of official account and video Number