题目链接: http://acm.oinsm.com/problem.php?cid=1022&pid=9
题目思路
题目读完,可能还是会有点朦朦的,题目意思就是,随意从一个点出发,问你是否能走到太平洋(即x == 1 || y == 1) 和 大西洋(即x == n || y == m), 然后看看数据范围,哦,可以搜!!( 或者是有别的解法!当然DFS,BFS 都是可以的!
搜法: 俗称逆向思维,既然要到太平洋,大西洋,那我们就从边界出发,往里搜,从太平洋过来的,我们标记为1,大西洋过来的标记为2,最后遍历一遍标记,就可以得到答案了!
代码
- DFS
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 155;
const int INF = 1e9;
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{
int x;
int y;
};
int n, m;
int mp[MAXN][MAXN];
bool vis[MAXN][MAXN][2];
bool check(int x, int y, int v) {
return !(x < 1 || x > n || y < 1 || y > m || vis[x][y][v - 1]);
}
void dfs(int x, int y, int v) {
for(int i = 0; i < 4; i++){
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if(check(xx, yy, v) && mp[x][y] <= mp[xx][yy]){
vis[xx][yy][v - 1] = true;
dfs(xx, yy, v);
}
}
}
int main()
{
ios::sync_with_stdio(false);
while(cin >> n >> m){
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> mp[i][j];
}
}
int sum = 0;
for(int i = 1; i <= m; i++){
vis[1][i][0] = true;
dfs(1, i, 1);
vis[n][i][1] = true;
dfs(n, i, 2);
}
for(int i = 1; i <= n; i++){
vis[i][1][0] = true;
dfs(i, 1, 1);
vis[i][m][1] = true;
dfs(i, m, 2);
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(vis[i][j][0] && vis[i][j][1]){
sum++;
}
}
}
cout << sum << endl;
}
return 0;
}
- BFS
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 155;
const int INF = 1e9;
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
struct node
{
int x;
int y;
};
int n, m;
int mp[MAXN][MAXN];
bool vis[MAXN][MAXN][2];
bool check(int x, int y, int v) {
return !(x < 1 || x > n || y < 1 || y > m || vis[x][y][v - 1]);
}
void bfs(int x, int y, int v) {
queue<node> q;
int ans = 0;
q.push(node{x, y});
while(!q.empty()) {
node tmp = q.front();
q.pop();
for(int i = 0; i < 4; i++){
int xx = tmp.x + dir[i][0];
int yy = tmp.y + dir[i][1];
if(check(xx, yy, v) && mp[tmp.x][tmp.y] <= mp[xx][yy]) {
vis[xx][yy][v - 1] = true;
q.push(node{xx, yy});
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
while(cin >> n >> m){
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cin >> mp[i][j];
}
}
int sum = 0;
for(int i = 1; i <= m; i++){
vis[1][i][0] = true;
bfs(1, i, 1);
vis[n][i][1] = true;
bfs(n, i, 2);
}
for(int i = 1; i <= n; i++){
vis[i][1][0] = true;
bfs(i, 1, 1);
vis[i][m][1] = true;
bfs(i, m, 2);
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(vis[i][j][0] && vis[i][j][1]){
sum++;
}
}
}
cout << sum << endl;
}
return 0;
}