当前位置:网站首页>[graph theory brush question-4] force deduction 778 Swimming in a rising pool
[graph theory brush question-4] force deduction 778 Swimming in a rising pool
2022-04-23 20:17:00 【smile-yan】
Graph theory brush questions
778. Swimming in a rising pool
Try to catch up with the original question Address
Difficulty and label
It's difficult
- Depth-first traversal
- Breadth first traversal
- And find
Title Description
In a n x n
The integer matrix of grid
in , The value of each square grid[i][j]
Indicate location (i, j)
The height of the platform .
When it began to rain , In time for t
when , The water level in the pool is t
. You can swim from one platform to any nearby platform , But the premise is that the water level must submerge both platforms at the same time . Suppose you can move an infinite distance in an instant , That is to say, it is not time-consuming to swim inside the grid by default . Of course , You have to stay in the grid when you swim .
You go from the top left platform of the grid (0,0)
set out . return You reach the lower right platform of the coordinate grid (n-1, n-1)
Minimum time required .
Example 1:
Input : grid = [[0,2],[1,3]]
Output : 3
explain :
Time is 0 when , Your position in the grid is (0, 0).
You can't swim in any direction at this time , Because the heights of platforms in four adjacent directions are greater than the current time of 0 The water level at the end of the day .
Wait for the time to arrive 3 when , You can swim to the platform (1, 1). Because the water level is 3, The platform in the coordinate grid has no comparison with the water level 3 Higher , So you can swim anywhere in the grid
Example 2:
Input : grid = [[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]
Output : 16
explain : The final route is marked in bold .
We have to wait for time for 16, Only at this time can the platform be guaranteed (0, 0) and (4, 4) It's connected
Tips :
n == grid.length
n == grid[i].length
1 <= n <= 50
0 <= grid[i][j] < n^2
grid[i][j] Each value in No duplication
Topic analysis
The topic is very interesting , But it's really hard . First of all, a simple understanding of the scene can assume that we are a duck , From you to [0, 0]
Swim home [n-1, n-1]
. Note that swim
get home , Therefore, the water must exceed the high platform to show that this road is accessible , Otherwise, the water is lower than the platform and you can't swim there .
Now combine the diagram 1, Be sure to wait until the water level reaches 3 Before you can pass .
Then we give the important conclusion of our reading topic :
- hypothesis
W = Max(grid)
, namely W Is the largest number of two-dimensional arrays , When the water level reachesW
There must be a way , The lovely duckling will be able to go home . - Our answer must be
[0, W]
Between .
So this topic turns to finding a threshold threshold
∈ [ 0 , W ] \in [0, W] ∈[0,W] , bring , When the water level reaches threshold
when , You can get at least one from [0, 0]
To [n-1, n-1]
The way home .
We have a two-dimensional array ary
, Size is n x n
, All defaults to 0.
Steps are as follows :
- Suppose the threshold is
Q
, For a two-dimensional arrayary
The position where the assignment is performed , The specific rules are :If grid[i][j] <= threshold Q, be ary[i][j] = 1, It means that this point can pass .
- Traverse ary, Find out if there is a path
[0, 0]
To[n-1, n-1]
.
Obviously , If Q
The bigger it is , The more points you can pass .
Code implementation 1—— DFS + Binary query
- initialization
visited
Array ,visited[i][j]
bytrue
Indicates that you have accessed or cannot access . - Write a DFS function , Traverse all paths . If you can reach your destination ( get home ) Just go back to true;
- Binary search threshold , Initialize each time according to the threshold visited Array , And then call DFS Function to check whether you can access .
Important supplement
:grid[0][0]
The location is not necessarily 0
, So the output is target
Must be greater than or equal to grid[0][0]
, Therefore, the starting point of binary search is grid[0][0]
, According to the subject conditions, the maximum value is also less than n*n
, So the end point of binary search is n*n-1
.
class Solution {
public:
const int dx[4] = {
0, 1, 0, -1};
const int dy[4] = {
1, 0, -1, 0};
/** * initialization visited Array , Place the unqualified points in true */
void initVisited(vector<vector<int>> grid,
vector<vector<bool>>& visited,
int threshold) {
int n = grid.size();
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
visited[i][j] = grid[i][j] > threshold;
}
}
}
/** * dfs Traverse */
bool dfs(vector<vector<bool>>& visited,
int x, int y) {
int n = visited.size();
// 1. Judge whether the destination is reached
if (x == n-1 && y == n-1) {
return true;
}
// 2. Tag has been accessed
visited[x][y] = true;
// 3. Depth-first traversal
for (int i=0; i<4; i++) {
int mx = x + dx[i];
int my = y + dy[i];
if (mx >= 0 && mx < n && my >= 0 && my < n && !visited[mx][my] ) {
// If you reach the end return otherwise continue for loop
if (dfs(visited, mx, my)) {
return true;
}
}
}
return false;
}
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
int left = grid[0][0];
int right = n*n-1;
vector<vector<bool>> visited(n, vector<bool>(n));
while (left < right) {
int mid = (left+right)/2;
initVisited(grid, visited, mid);
if (dfs(visited, 0, 0)) {
right = mid;
} else {
left = mid+1;
}
}
// left == right
return left;
}
};
- Time complexity : O ( N 2 log N ) O(N^2 \log N) O(N2logN)
- Spatial complexity : O ( N 2 ) O(N^2) O(N2)
Additional explanation : If the topic does not emphasize the value range of each point , Then you can first find the largest and smallest , Then make a binary query , Same effect , Does not affect the overall time .
in addition , This problem is not the shortest path problem , The concern is how much water the ducklings can pass through , therefore , Even if there may be many paths in the end , We just need to make sure we have one that we can go with .
summary
It is basically the same as the official explanation , But the algorithm 1 My idea is to attach additional conditions to visited
Array , dfs Basically nothing has changed .
If you understand the meaning of this topic , The only error prone thing should be Dichotomy search threshold . In fact, I passed all the test cases first and prompted to timeout , After reading the official source code, I remembered to find it by dichotomy .
In a word, it is an interesting topic , Never be difficult
Two words bluff .
Smileyan
2022.3.22 17:08
版权声明
本文为[smile-yan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210553133212.html
边栏推荐
- Paper writing 19: the difference between conference papers and journal papers
- Use the rolling division method to find the maximum common divisor of two numbers
- 微信中金财富高端专区安全吗,证券如何开户呢
- 【问题解决】‘ascii‘ codec can‘t encode characters in position xx-xx: ordinal not in range(128)
- Handwritten Google's first generation distributed computing framework MapReduce
- nc基础用法2
- CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
- R语言使用econocharts包创建微观经济或宏观经济图、indifference函数可视化无差异曲线、自定义计算交叉点、自定义配置indifference函数的参数丰富可视化效果
- Livego + ffmpeg + RTMP + flvjs to realize live video
- Intersection calculation of straight line and plane in PCL point cloud processing (53)
猜你喜欢
Leetcode XOR operation
CVPR 2022 | QueryDet:使用级联稀疏query加速高分辨率下的小目标检测
PHP reference manual string (7.2000 words)
Fundamentals of network communication (LAN, Wan, IP address, port number, protocol, encapsulation and distribution)
[numerical prediction case] (3) LSTM time series electricity quantity prediction, with tensorflow complete code attached
Numpy mathematical function & logical function
PCL点云处理之计算两平面交线(五十一)
How to create bep-20 pass on BNB chain
Sqoop imports tinyint type fields to boolean type
Fundamentals of programming language (2)
随机推荐
DNS cloud school rising posture! Three advanced uses of authoritative DNS
Remote code execution in Win 11 using wpad / PAC and JScript 3
R语言使用caret包的preProcess函数进行数据预处理:对所有的数据列进行BoxCox变换处理(将非正态分布数据列转换为正态分布数据、不可以处理负数)、设置method参数为BoxCox
山东大学软件学院项目实训-创新实训-网络安全靶场实验平台(八)
Paper writing 19: the difference between conference papers and journal papers
Record: call mapper to report null pointer Foreach > the usage of not removing repetition;
R language uses the preprocess function of caret package for data preprocessing: BoxCox transform all data columns (convert non normal distribution data columns to normal distribution data and can not
Openharmony open source developer growth plan, looking for new open source forces that change the world!
Handwritten Google's first generation distributed computing framework MapReduce
nc基础用法2
Computing the intersection of two planes in PCL point cloud processing (51)
Servlet learning notes
R语言ggplot2可视化分面图(facet_wrap)、使用lineheight参数自定义设置分面图标签栏(灰色标签栏)的高度
WordPress插件:WP-China-Yes解决国内访问官网慢的方法
使用 WPAD/PAC 和 JScript在win11中进行远程代码执行1
SRS 的部署
Project training of Software College of Shandong University - Innovation Training - network security shooting range experimental platform (6)
The flinkcdc reports an error: but this is no longer available on the server
2022 - Data Warehouse - [time dimension table] - year, week and holiday
Cadence Orcad Capture CIS更换元器件之Link Database 功能介绍图文教程及视频演示