滴滴笔试,青蛙寻路,AC率50%,错在哪?

#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool hasPath(vector< vector<int> > &res, vector< vector<int> > &vec,int n,int m, int row, int col, int P) {
	if (row == 0 && col == m - 1 && P >= 0) {
		return true;
	}
	bool canArrive = false;
	if (row >= 0 && row < n && col >= 0 && col < m && vec[row][col] == 1 && P >= 0) {
		res.push_back({ row,col });
		canArrive = hasPath(res, vec, n, m, row - 1, col, P - 3) ||
			hasPath(res, vec, n, m, row + 1, col, P) ||
			hasPath(res, vec, n, m, row, col - 1, P - 1) ||
			hasPath(res, vec, n, m, row, col + 1, P - 1);
		if (!canArrive) {
			res.pop_back();
		}
	}
	return canArrive;
}
int main() {
	int n, m, P;
	while (cin >> n >> m >> P) {
		vector<vector<int>> vec(n, vector<int>(m, 0));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cin >> vec[i][j];
			}
		}
		vector<vector<int>> res;
		bool canArrive = hasPath(res, vec, n, m, 0, 0, P);
		if (canArrive) {
			int i = 0;
			for (; i < res.size() - 1; i++)
			{
				cout << "[" << res[i][0] << "," << res[i][1] << "]" << ",";
			}
			cout << "[" << res[i][0] << "," << res[i][1] << "]" << "\n";
		}
		else
			cout << "Can not escape!" << "\n";
	}
	return 0;
} 提示我运行超时,可能是循环太多,然后通过率50%
我把输出结果改用string来存,不用vector,最后直接输出string,还是不行,一样的提示。
我感觉没啥问题啊...

全部评论
#include<iostream> #include<string.h> #include<vector> using namespace std; int a[11][11]; int flag[11][11]; vector<int> xMax; vector<int> yMax; int pMax; void dfs(int maze[11][11],int ff[11][11],int x,int y,int p,int n,int m,vector<int> xPath,vector<int> yPath,int &maxP){ if (p < 0){ return; } if (x==0&&y==m-1){ if (maxP < p){ maxP = p; xMax = xPath; yMax = yPath; } return; } int xx[4] = {-1,1,0,0}; int yy[4] = { 0, 0, -1, 1 }; int price[4] = {3,0,1,1}; int i; for (i = 0; i < 4;i++){ int sx = x + xx[i]; int sy = y + yy[i]; if (sx >= 0 && sx < n&&sy >= 0 && sy < m&&!ff[sx][sy]&&maze[sx][sy]){ ff[sx][sy] = 1; xPath.push_back(sx); yPath.push_back(sy); dfs(maze,ff,sx,sy,p-price[i],n,m,xPath,yPath,maxP); ff[sx][sy] = 0; xPath.pop_back(); yPath.pop_back(); } } } int main(){ int n,m; while (cin>>n>>m>>pMax){ memset(a,0,sizeof(a)); memset(flag,0,sizeof(flag)); int i, j; for (i = 0; i < n;i++){ for (j = 0; j < m; j++) { int tmp; cin >> tmp; a[i][j]=tmp; } } flag[0][0] = 1; vector<int> xPath, yPath; xPath.push_back(0); yPath.push_back(0); int mm = -100; dfs(a,flag,0,0,pMax,n,m,xPath,yPath,mm); if (mm == -100){ cout << "Can not escape!" << endl; continue; } for (i = 0; i < xMax.size(); i++){ cout << "[" << xMax[i] << "," << yMax[i] << "]"; if (i<xMax.size()-1) cout << ","; } cout << endl; } system("pause"); return 0; } 难得一次全部AC的笔试
点赞 回复 分享
发布于 2016-09-18 17:39
同  一开始以为每走一步都是相同的消耗1,结果是AC90%……  后来按题意改了之后还是90%…… 这个用例有点无语……
点赞 回复 分享
发布于 2016-09-18 17:25
其实是水题 改了一堆 ac 80% 我也已经比如水笔了...
点赞 回复 分享
发布于 2016-09-18 17:26
题意是要求消耗体力最短的路径啊
点赞 回复 分享
发布于 2016-09-18 17:30
优先队列广搜,水过。。。不过广搜输出比较麻烦,需要把点串起来
点赞 回复 分享
发布于 2016-09-19 00:13

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务