BFS
#include <iostream>
#include <queue>
using namespace std;
const int N = 1010;
int graph[N][N];
bool st[N][N];
typedef pair<int, int> pii;
int n;
int dic[8][2] = {
{-1, -1}, {-1, 0}, {-1, 1}, {0, -1},
{0, 1}, {1, -1}, {1, 0}, {1, 1}
};
void bfs(int x, int y, bool& is_peak, bool& is_valley){
queue<pii> qu;
qu.push({x, y});
st[x][y] = true;
while(!qu.empty()){
pii now = qu.front();
qu.pop();
for(int i = 0; i < 8; i ++ ){
int xx = now.first + dic[i][0];
int yy = now.second + dic[i][1];
if(xx < 0 || xx >= n || yy < 0 || yy >= n) continue;
if(graph[xx][yy] > graph[now.first][now.second]) is_peak = false;
if(graph[xx][yy] < graph[now.first][now.second]) is_valley = false;
if(graph[xx][yy] == graph[now.first][now.second] && !st[xx][yy]){
qu.push({xx, yy});
st[xx][yy] = true;
}
}
}
}
int main(){
cin >> n;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
cin >> graph[i][j];
}
}
int peak, valley;
peak = valley = 0;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
if(st[i][j]) continue;
bool is_peak, is_valley;
is_peak = is_valley = true;
bfs(i, j, is_peak, is_valley);
if(is_peak) peak ++ ;
if(is_valley) valley ++ ;
}
}
cout << peak << " " << valley << endl;
return 0;
}
DFS
#include <iostream>
using namespace std;
const int N = 1E3 + 10;
int graph[N][N];
bool vis[N][N];
int n;
bool is_peak, is_valley;
int dx[8] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};
void read(){
cin >> n;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ) cin >> graph[i][j];
}
}
void dfs(int x, int y){
for(int i = 0; i < 8; i ++ ){
int xx = x + dx[i], yy = y + dy[i];
if(xx < 0 || xx >= n || yy < 0 || yy >= n) continue;
if(graph[xx][yy] > graph[x][y]) is_peak = false;
else if(graph[xx][yy] < graph[x][y]) is_valley = false;
else{
if(vis[xx][yy]) continue;
vis[xx][yy] = true;
dfs(xx, yy);
}
}
}
int main(){
read();
int peak = 0, valley = 0;
for(int i = 0; i < n; i ++ ){
for(int j = 0; j < n; j ++ ){
if(vis[i][j]) continue;
is_peak = true, is_valley = true;
vis[i][j] = true;
dfs(i, j);
peak += is_peak;
valley += is_valley;
}
}
cout << peak << ' ' << valley << endl;
return 0;
}
dfs为什么会超时呀
写错了吧
我也不知道到第7个案例不行了
https://www.acwing.com/solution/content/65209/ 对比一下
妙哇
好🔥