gpt4 book ai didi

algorithm - 关于 SPOJ TOURIST 的查询

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:49 25 4
gpt4 key购买 nike

问题陈述:

A lazy tourist wants to visit as many interesting locations in a city as possible without going one step further than necessary. Starting from his hotel, located in the north-west corner of city, he intends to take a walk to the south-east corner of the city and then walk back. When walking to the south-east corner, he will only walk east or south, and when walking back to the north-west corner, he will only walk north or west. After studying the city map he realizes that the task is not so simple because some areas are blocked. Therefore he has kindly asked you to write a program to solve his problem.

Given the city map (a 2D grid) where the interesting locations and blocked areas are marked, determine the maximum number of interesting locations he can visit. Locations visited twice are only counted once.

Input

The first line in the input contains the number of test cases (at most 20). Then follow the cases. Each case starts with a line containing two integers, W and H (2 ≤ W , H ≤ 100), the width and the height of the city map. Then follow H lines, each containing a string with W characters with the following meaning:

 . Walkable area * Interesting location (also walkable area) # Blocked area

You may assume that the upper-left corner (start and end point) and lower-right corner (turning point) are walkable, and that a walkable path of length H + W − 2 exists between them.

Output

For each test case, output a line containing a single integer: the maximum number of interesting locations the lazy tourist can visit.

Example

Input:    2 9 7*........ .....**#.  ..**...#*  ..####*#.  .*.#*.*#.  ...#**...*........ 5 5  .*.*.*###.*.*.*  .###*  .*.*.

Output: 7 8

我的解决方案:

#include <iostream>

using namespace std;

char path[101][101];
int sz1,sz2;
int solve(int a,int b,int i,int j){
if(a>=sz1||b>=sz2||i>=sz1||j>=sz2){
return 0;
}
int c = 0;
if(path[a][b]=='#'||path[i][j]=='#')
return -100;
if(path[a][b]=='*'){
c = 1;
}
if(path[i][j]=='*'&&a!=i)
c++;
int x =max(max(solve(a,b+1,i+1,j),solve(a+1,b,i+1,j)),max(solve(a,b+1,i,j+1),solve(a+1,b,i,j+1)));

return x+c;
}

int main()
{
int t;
cin>>t;
while(t--){
cin>>sz1>>sz2;

for(int i=0;i<sz1;i++){
for(int j=0;j<sz2;j++)
cin>>path[i][j];
}

cout << solve(0,0,0,0) << endl;
}
}

我还没有使用内存,因为我只是想写一个回溯函数。但是我对第一个测试用例的回答是错误的。正确答案是 7,但这段代码打印出 10。这个递归解决方案有什么问题?

最佳答案

你应该交换 sz1 和 sz2。

输入的第一行分别给出了列数和行数。但你以相反的顺序对待它们。

关于algorithm - 关于 SPOJ TOURIST 的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38450248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com