NC207972. 我竟然不会跳方格
描述
输入描述
输入有多组,组数不超过10每组第一行2个数字,分别表示矩形空地的大小n和m,n和m均小于45接下来有n行,每行有m个数字,表示在格子上的数字,数字绝对值不超过1000
输出描述
每组输入输出一行,3个数,分别代表最长路径长度,此时的纵向坐标和横向坐标
示例1
输入:
2 3 14 0 9 4 18 18 2 3 1 1 2 1 1 2
输出:
3 1 2 2 1 2
说明:
第2个样例2个2都可以作为最长路的终点,多个终点可选时输出纵向坐标较大者,即(1,2),注意坐标原点从0 0开始示例2
输入:
7 9 2 5 2 5 8 6 17 17 12 12 9 14 1 9 16 9 8 12 5 15 14 9 1 12 5 0 18 13 19 3 19 16 7 9 9 17 6 9 13 15 17 16 6 5 8 2 15 14 14 1 16 11 6 3 13 15 5 13 12 8 12 5 13
输出:
6 5 1
C++11(clang++ 3.9) 解法, 执行用时: 15ms, 内存消耗: 612K, 提交时间: 2020-06-19 17:15:33
#include<iostream> #include<vector> #include<algorithm> #include<string> #include<queue> using namespace std; int n, m; int xx[4] = { 1,-1,0,0 }; int yy[4] = { 0,0,-1,1 }; struct pos { int len; int x; int y; }; bool compare(pos a, pos b) { if (a.len != b.len) { return a.len > b.len ? true : false; } else { return a.x == b.x ? (a.y > b.y) : (a.x > b.x); } } pos func(int x, int y, const vector<vector<int>>& matrix) { pos cur; cur.len = 1; cur.x = x; cur.y = y; queue<pos>q; q.push(cur); while (!q.empty()) { pos t = q.front(); int cur_len = t.len; int cur_x = t.x; int cur_y = t.y; q.pop(); //int f = 1; for (int i = 0; i < 4; i++) { int nx = cur_x + xx[i]; int ny = cur_y + yy[i]; if (nx >= 0 && nx < n && ny >= 0 && ny<m && matrix[nx][ny]>matrix[cur_x][cur_y]) { //f = 0; pos temp; temp.len = cur_len + 1; temp.x = nx; temp.y = ny; q.push(temp); } } //if (1) { if (compare(t, cur)) { cur = t; } // } } return cur; } int main() { while (cin >> n >> m) { vector<vector<int>>matrix(n, vector<int>(m, 0)); pos cur; cur.len = 0; cur.x = 0; cur.y = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> matrix[i][j]; } } for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { pos temp = func(i, j, matrix); if (compare(temp, cur)) { cur = temp; } } } cout << cur.len << " " << cur.x << " " << cur.y << endl; } system("pause"); }
C++14(g++5.4) 解法, 执行用时: 8ms, 内存消耗: 496K, 提交时间: 2020-06-17 17:12:30
#include <iostream> using namespace std; const int N=45; int maze[N][N]; int n,m; int end_x,end_y; int ans; int dx[4]={0,-1,1,0}; int dy[4]={1,0,0,-1}; void dfs(int cur_i,int cur_j,int cnt){ if(cnt>ans||(cnt==ans&&cur_i>end_x)||(cnt==ans&&cur_i==end_x&&cur_j>end_y)){ end_x=cur_i;end_y=cur_j;ans=cnt; } for(int i=0;i<4;i++){ int ii=cur_i+dx[i]; int jj=cur_j+dy[i]; if(ii>=0&&jj>=0&&ii<n&&jj<m&&maze[ii][jj]>maze[cur_i][cur_j]){ dfs(ii,jj,cnt+1); } } } int main() { while(cin>>n>>m) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) cin >> maze[i][j]; ans=0; for(int i=0;i<n;i++) for(int j=0;j<m;j++) dfs(i,j,0); cout<<ans+1<<" "<<end_x<<" "<<end_y<<endl; } return 0; }