振兴中华

标题: 振兴中华
    小明参加了学校的趣味运动会,其中的一个项目是:跳格子。

    地上画着一些格子,每个格子里写一个字,如下所示:(也可参见p1.jpg)

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

起振兴中华



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

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

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

答案是一个整数,请通过浏览器直接提交该数字。

注意:不要提交解答过程,或其它辅助说明类的内容



import java.util.*;
import java.math.*;

class State
{
	int map[] = new int[8];
	int step;
	int x = 0 , y = 0;
	public State(){}
	public State(State state)
	{
		setMap(state.map);
		step = state.step;
		x = state.x;
		y = state.y;
	}
	public void setMap(int Map[])
	{
		for(int i = 0; i < 8; i++)
			map[i] = Map[i];
	}
}


public class Main
{
	//从我做起振兴中华
	//1 2 3 45 6 7 8
	static int map[][] = {{1,2,3,4,5},{2,3,4,5,6},{3,4,5,6,7},{4,5,6,7,8}};
	static int dir_x[] = {1,0,-1,0};
	static int dir_y[] = {0,1,0,-1};
	
	public static boolean bfs(State state, int dir)
	{
		int temp_x , temp_y;
		
		if(state.step > 8) return false;
		//出界
		if(state.x+dir_x[dir] < 0 || state.x+dir_x[dir] >= 4) return false;
		if(state.y+dir_y[dir] < 0 || state.y+dir_y[dir] >= 5) return false;
		
		//继续前行
		temp_x = state.x + dir_x[dir];
		temp_y = state.y + dir_y[dir];
		if(state.map[state.step-1] + 1 != map[temp_x][temp_y]) return false;
		
		state.x = temp_x;
		state.y = temp_y;
		state.map[state.step] = map[state.x][state.y];
		state.step++;
		return true;
	}
	
	public static boolean isOk(State state)
	{
		int flag = 1;
		if(state.step != 8) return false;
		for(int i = 0; i < state.step - 1; i++)
		{
			if(state.map[i] != i+1)
			{
				flag = 0;
				break;
			}
		}
		if(flag == 1) return true;
		else return false;
	}
	
	public static void main(String[] args)
	{
		int count = 0;
		Queue<State>q = new LinkedList<State>();
		//起始位置
		State state = new State();
		state.map[0] = 1;
		state.step = 1;
		q.add(state);
		
		while(!q.isEmpty())
		{
			State temp1 = new State();
			temp1 = q.remove();
			
			if(isOk(temp1)) count++;
			for(int i = 0; i < 4; i++)
			{
				State temp2 = new State(temp1);
				if(bfs(temp2, i))
				{
					q.add(temp2);
				}
			}
		}
		System.out.println(count);
	}//main()
}//class Main


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值