NC220471. EfficientlyElevated
描述
A visualisation of the second sample input.
输入描述
The input consists of:
- One line containing integers and (), the height and width of the grid.
- lines of integers each, where (), the th integer on the th line, denotes the number of floors at position of the grid.
输出描述
Output the minimum number of elevators you need to build to be able to reach every part of the building(s) in the grid.
示例1
输入:
3 3 1 2 3 0 0 4 7 6 5
输出:
1
示例2
输入:
6 7 0 0 0 0 0 0 0 0 1 2 3 2 1 0 0 1 2 3 2 1 0 0 0 0 0 0 0 0 0 1 0 5 0 0 0 0 0 0 0 0 0 0
输出:
2
示例3
输入:
4 4 1 1 2 1 2 2 1 2 1 2 2 1 2 1 2 2
输出:
4
C++(clang++11) 解法, 执行用时: 114ms, 内存消耗: 37244K, 提交时间: 2021-04-08 13:03:00
#include <bits/stdc++.h> using namespace std; int i,j,k,n,m,res,a[505][505]; vector<vector<int> >v; void dfs(int x,int y){ if(!a[x][y]){return;} //printf("%d %d\n",x,y); int tmp=a[x][y];a[x][y]=0; if(a[x-1][y]<=tmp){dfs(x-1,y);} if(a[x+1][y]<=tmp){dfs(x+1,y);} if(a[x][y-1]<=tmp){dfs(x,y-1);} if(a[x][y+1]<=tmp){dfs(x,y+1);} } int main(){ scanf("%d%d",&n,&m); for(i=1;i<=n;i++){ for(j=1;j<=m;j++){ scanf("%d",&a[i][j]); if(a[i][j]==1){a[i][j]=0;} v.push_back({-a[i][j],i,j}); } } sort(v.begin(),v.end()); for(auto i:v){ if(a[i[1]][i[2]]){dfs(i[1],i[2]);res++;} } printf("%d",res); }