蓝桥杯题目_振兴中华

地上画着一些格子,每个格子里写一个字,如下所示:

从我做起振
我做起振兴
做起振兴中
起振兴中华

蓝桥杯题目_振兴中华_第1张图片


    比赛时,先站在左上角的写着“从”字的格子里,可以横向或纵向跳到相邻的格子里,但不能跳到对角的格子或其它位置。一直要跳到“华”字结束。


    要求跳过的路线刚好构成“从我做起振兴中华”这句话。

    请你帮助小明算一算他一共有多少种可能的跳跃路线呢?

 


本例子是使用dfs深搜路径来实现的

本题主要是求起点走到终点有多少种可能。起点为从字,坐标(0,0)。华字为终点,坐标(3,4)

    public static int map[][]=new int[4][5];//地图
	public static int book[][]=new int[4][5];//标记
	public static int p=3,q=4;//终点 起点为0,0
	public static int count=0; //计数器
	public static void dfs(int x,int y) {
		//到达终点
		if(x==p&&y==q) {
			count++;
			return;
		}
		//移动路径 上下左右
		int next[][]= {{0,1},
						{1,0},
						{0,-1},
						{-1,0}
						};
	
		//开始移动
		for(int i=0;i<4;i++) {
			int tx=x+next[i][0];
			int ty=y+next[i][1];
		
			//不能移动出界
			if(tx<0||ty<0||tx>=4||ty>=5)
				continue;
			
			if(book[tx][ty]==0) {
				book[tx][ty]=1; //标记已经走过地点
				dfs(tx, ty);
				book[tx][ty]=0; //回溯
			}
			
			
		}
		
		
		
		
		
	}
	public static void main(String[] args) {
		book[0][0]=1;//标记起点已经被走过
		dfs(0, 0);//起点为0,0
		//count=976
		System.out.println("有"+count+"种可能");
	}

 

你可能感兴趣的:(算法题)