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 + "]";
}
}
}
【算法】程序猿不写代码是不对的64
最新推荐文章于 2023-12-24 16:00:47 发布