【算法】程序猿不写代码是不对的64

package com.kingdz.algorithm.time201705;

/**
 * <pre>
 * 水管工问题
 * 1代表从上到右,2代表从下到右,3代表从下到左,4代表从上到左,5代表从左到右,6代表从上到下
 * 表示水管的状态,给出入口和出口位置,转动水管
 * </pre>
 * 
 * @author kingdz
 * 
 */
public class Algo31 {

	private static int[][] source;
	private static int[][] mark = new int[51][51];
	private static int targetX;
	private static int targetY;

	// 标记是否已经结束
	private static int flag = 0;
	private static Node[] list = new Node[100];;
	private static int top = 0;

	public static void main(String[] args) {
		targetX = 5;
		targetY = 4;
		source = new int[][] { { 5, 3, 5, 3 }, { 1, 5, 3, 0 }, { 2, 3, 5, 1 }, { 6, 1, 1, 5 }, { 1, 5, 5, 4 } };
		dfs(0, 0, 1);
		for (int i = 0; i < list.length; i++) {
			if (list[i] == null) {
				break;
			}
			System.out.println(list[i]);
		}
	};

	public static void dfs(int x, int y, int front) {
		if (flag == 1) {
			return;
		}

		if (x == targetX - 1 && y == targetY) {
			flag = 1;
			System.out.println("找到铺设方案");
			return;
		}

		if (x < 0 || x >= source.length || y < 0 || y >= source[0].length) {
			// 越界
			return;
		}

		if (mark[x][y] == 1) {
			// 已经使用过该水管
			return;
		}

		mark[x][y] = 1;
		list[top] = new Node(x, y);
		top++;

		if (source[x][y] >= 5 && source[x][y] <= 6) {
			// 当前水管是直管
			if (front == 1) {
				// 进水口在左边
				dfs(x, y + 1, 1);
			}
			if (front == 2) {
				// 进水口在上边
				dfs(x + 1, y, 2);
			}
			if (front == 3) {
				// 进水口在右边
				dfs(x, y - 1, 3);
			}
			if (front == 4) {
				// 进水口在下边
				dfs(x - 1, y, 4);
			}
		}

		if (source[x][y] >= 1 && source[x][y] <= 4) {
			// 当前水管是弯管
			if (front == 1) {
				// 进水口在左边
				dfs(x + 1, y, 2);
				dfs(x - 1, y, 4);
			}
			if (front == 2) {
				// 进水口在上边
				dfs(x, y + 1, 1);
				dfs(x, y - 1, 3);
			}
			if (front == 3) {
				// 进水口在右边
				dfs(x - 1, y, 4);
				dfs(x + 1, y, 2);
			}
			if (front == 4) {
				// 进水口在下边
				dfs(x, y + 1, 1);
				dfs(x, y - 1, 3);
			}
		}

		mark[x][y] = 0;
		top--;
		return;
	}

	private static class Node {
		int x;
		int y;

		public Node(int x, int y) {
			super();
			this.x = x;
			this.y = y;
		}

		@Override
		public String toString() {
			return "Node [x=" + x + ", y=" + y + "]";
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值