题目地址:http://community.topcoder.com/stat?c=problem_statement&pm=1889&rd=4709
题目描述:在整数坐标系中,找从(0,0)到(width,height)的不同路径,每条路径的长度必须是width+height,这说明点只能向右和向上移动。并且还有一些坐标之间的路径是不能经过的。
思路:grid[i][j]表示从(0,0)到(i,j)不同路径的数目,则grid[i][j]=gird[i-1][j]+grid[i][j-1]
public class AvoidRoads {
long[][] grid = null;
int[][][][] edges = null;
public long numWays(int width,int height,String[] bad){
grid = new long[width+1][height+1];
edges = new int[width+1][height+1][width+1][height+1];
for(String line: bad){
String[] num = line.split(" ");
int x1 = Integer.parseInt(num[0]);
int y1 = Integer.parseInt(num[1]);
int x2 = Integer.parseInt(num[2]);
int y2 = Integer.parseInt(num[3]);
if(y1==y2 || x1==x2){
edges[x1][y1][x2][y2] = -1;
edges[x2][y2][x1][y1] = -1;
}else{
int max_X = x1>x2 ? x1:x2;
int max_Y = y1>y2 ? y1:y2;
int min_X = x1<x2 ? x1:x2;
int min_Y = y1<y2 ? y1:y2;
if((max_X==x1&&max_Y==y1)||(max_X==x2&&max_Y==y2)){
edges[min_X][min_Y][min_X][max_Y] = -1;
edges[min_X][min_Y][max_X][min_Y] = -1;
edges[min_X][max_Y][max_X][max_Y] = -1;
edges[max_X][min_Y][max_X][max_Y] = -1;
//dual
edges[min_X][max_Y][min_X][min_Y] = -1;
edges[max_X][min_Y][min_X][min_Y] = -1;
edges[max_X][max_Y][min_X][max_Y] = -1;
edges[max_X][max_Y][max_X][min_Y] = -1;
}else{
edges[min_X][max_Y][min_X][min_Y] = -1;
edges[min_X][max_Y][max_X][max_Y] = -1;
edges[max_X][min_Y][min_X][min_Y] = -1;
edges[max_X][min_Y][max_X][max_Y] = -1;
//dual
edges[min_X][min_Y][min_X][max_Y] = -1;
edges[max_X][max_Y][min_X][max_Y] = -1;
edges[min_X][min_Y][max_X][min_Y] = -1;
edges[max_X][max_Y][max_X][min_Y] = -1;
}
}
}
grid[0][0] = 1;
for(int i=0;i<=width;i++)
for(int j=0;j<=height;j++)
{
if(i==0&&j==0) continue;
long temp = 0;
if(i-1>=0&&edges[i-1][j][i][j]!=-1)
temp +=grid[i-1][j];
if(j-1>=0&&edges[i][j-1][i][j]!=-1)
temp +=grid[i][j-1];
grid[i][j] = temp;
}
return grid[width][height];
}
}