//Here is the code:
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
import java.io.*;
public class ABCPATH {
public static int computeLongest(char[][] connect, int i, int j, int[][] dp) {
if (dp[i][j] != 0) {
return dp[i][j];
}
int max = 1;
char c = connect[i][j];
c++;
int dy[] = {0, 0, -1, 1, 1, -1, 1, -1};
int dx[] = {-1, 1, 0, 0, 1, 1, -1, -1};
for (int k = 0; k < dx.length; k++) {
int inew = i + dy[k];
int jnew = j + dx[k];
if (inew >= 0 && inew < connect.length && jnew >= 0 && jnew < connect[0].length) {
if (connect[inew][jnew] == c) {
return dp[i][j] = Math.max(max, 1 + computeLongest(connect, inew, jnew, dp));
}
}
}
return max;
}
public static void main(String[] args) throws IOException {
//Scanner s = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
int k = 1;
int p = 1;
while (k != -1) {
String in[] = sc.nextLine().split(" ");
if (Integer.parseInt(in[0]) != 0 && Integer.parseInt(in[1]) != 0) {
int r = Integer.parseInt(in[0]);
int c = Integer.parseInt(in[1]);
char[][] connect = new char[r][c];
for (int i = 0; i < r; i++) {
String in2 = sc.nextLine();
for (int j = 0; j < in2.length(); j++) {
connect[i][j] = in2.charAt(j);
}
}
int max = 0;
int dp[][] = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (connect[i][j] == 'A') {
max = Math.max(max, computeLongest(connect, i, j, dp));
}
}
}
System.out.println("Case " + p + ": " + max);
p++;
}
else {
k = -1;
}
}
}
}
问题的链接是:http://www.spoj.com/problems/ABCPATH/,即使在测试1上,它也给出了错误的答案。但我使用的算法是正确的,因为我已经从一些人那里得到了证实 提交成功。
答案 0 :(得分:0)
来自SPOJ的样本输入给了我正确答案:
案例1:4
您能提供产生错误结果的输入吗?
好的,帮助你一点。考虑这些案例:
3 3
ABC
BFG
CDE
0 0
3 3
ABC
BFD
CGE
0 0
他们应该返回相同的结果,但他们不会。
答案 1 :(得分:-2)
对dp[i][j]
的表述进行一点改动可能有所帮助。
而不是在for循环中计算dp[i][j]
尝试找到最大路径长度,即最大可能的8种可能性,然后将其与dp[i][j]
进行对比。
片段可能会有所帮助:
int dfs(int i,int j)
{
if(dp[i][j]!=0)
{
return dp[i][j];
}
int val=1;
for(int k=0;k<8;k++)
{
int i1=i+x[k];
int j1=j+y[k];
if(i1>=0&&i1<h&&j1>=0&&j1<w)
{
if((mat[i1][j1]==mat[i][j]+1 )&& visit[i1][j1]==0)
{
//path++; //important don't do this in recursive functions with for loops
visit[i1][j1]=1;
//return(dp[i][j]=max(path ,dfs(i1,j1,path+1)));//this is causing problem here
val=max(val ,1+dfs(i1,j1));
}
}
}
return(dp[i][j]=val);
}