盲目搜索算法实现八数码问题

package com.jn.rz.实验一;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

/**
 * @author 江南大学1033190417
 * @date 2022/3/31 11:36
 */
public class Status implements Serializable {

    public int[][] status;//状态元素

    public Integer depth;

    public List<Status> path = new ArrayList<>();//路径

    public Status(int[][] status) {
        this.status = status;
    }

    public List<Status> getChildStatus() {
        List<Status> childStatus = new ArrayList<>();
        if (left()) {
            Status s = new Status(copyArray(this.status));
            s.depth = this.depth + 1;
            childStatus.add(s);
            right();
        }
        if (up()) {
            Status s = new Status(copyArray(this.status));
            s.depth = this.depth + 1;
            childStatus.add(s);
            down();
        }

        if (down()) {
            Status s = new Status(copyArray(this.status));
            s.depth = this.depth + 1;
            childStatus.add(s);
            up();
        }
        if (right()) {
            Status s = new Status(copyArray(this.status));
            s.depth = this.depth + 1;
            childStatus.add(s);
            left();
        }
        return childStatus;
    }

    //上移动,相对0来说
    public boolean up() {
        int[] coordinateOf0 = getCoordinateOf0();
        int x = coordinateOf0[0];
        int y = coordinateOf0[1];
        try {
            this.status[x][y] = this.status[x - 1][y];
            this.status[x - 1][y] = 0;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //下移
    public boolean down() {
        int[] coordinateOf0 = getCoordinateOf0();
        int x = coordinateOf0[0];
        int y = coordinateOf0[1];
        try {
            this.status[x][y] = this.status[x + 1][y];
            this.status[x + 1][y] = 0;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //左移
    public boolean left() {
        int[] coordinateOf0 = getCoordinateOf0();
        int x = coordinateOf0[0];
        int y = coordinateOf0[1];
        try {
            this.status[x][y] = this.status[x][y - 1];
            this.status[x][y - 1] = 0;
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //右移
    public boolean right() {
        int[] coordinateOf0 = getCoordinateOf0();
        int x = coordinateOf0[0];
        int y = coordinateOf0[1];
        try {
            this.status[x][y] = this.status[x][y + 1];
            this.status[x][y + 1] = 0;
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 定位0的位置
     *
     * @return 横纵坐标
     */
    public int[] getCoordinateOf0() {
        for (int i = 0; i < this.status.length; i++) {
            for (int j = 0; j < this.status[i].length; j++) {
                if (this.status[i][j] == 0) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{-1, -1};
    }

    //深拷贝数组
    public static int[][] copyArray(int[][] input) {
        int[][] output = new int[input.length][input[0].length];
        for (int i = 0; i < input.length; i++) {
            for (int j = 0; j < input[i].length; j++) {
                output[i][j] = input[i][j];
            }
        }
        return output;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Status status1 = (Status) o;
        for (int i = 0; i < this.status.length; i++) {
            for (int j = 0; j < this.status[i].length; j++) {
                if (this.status[i][j] != status1.status[i][j])
                    return false;
            }
        }
        return true;
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < this.status.length; i++) {
            for (int j = 0; j < this.status[i].length; j++) {
                result.append(this.status[i][j]).append("\t");
            }
            result.append("\n");
        }
        return result.toString();
    }

    public static void main(String[] args) throws Exception {
        int[][] start = new int[3][3];//初始状态
        int[][] end = new int[3][3];//目标状态
        Stack<Status> open = new Stack<>();//open表
        Stack<Status> closed = new Stack<>();//closed表
        int depth = 5;//深度限制

        FileInputStream fis = new FileInputStream("D:\\桌面\\人工智能\\实验\\src\\com\\jn\\rz\\实验一\\input.txt");
        InputStreamReader dis = new InputStreamReader(fis);
        BufferedReader reader = new BufferedReader(dis);
        String s;
        int hang = 0;//行号标记
        while ((s = reader.readLine()) != null) {
            if ("".equals(s))
                continue;
            if (s.contains("depth")) {
                depth = Integer.parseInt(s.split(" ")[1]);
                continue;
            }
            String[] split = s.split(" ");
            if (hang >= 3) {
                for (int i = 0; i < 3; i++) {
                    end[hang % 3][i] = Integer.parseInt(split[i]);
                }
                hang++;
            } else {
                for (int i = 0; i < 3; i++) {
                    start[hang % 3][i] = Integer.parseInt(split[i]);
                }
                hang++;
            }
        }

        Status startStatus = new Status(start);
        startStatus.depth = 1;
        Status endStatus = new Status(end);
        open.add(startStatus);

        while (!open.isEmpty()) {
            Status n = open.pop();
            n.path.add(n);
            System.out.println(n);//输出遍历的过程
            closed.add(n);
            if (n.equals(endStatus)) {
                System.out.println("解路长度:"+n.path.size());
                System.out.println("找到的解");
                for (Status status : n.path) {
                    System.out.println(status);
                }
               break;
            }
            if (n.depth == depth) {
                continue;
            }
            //得到所有子状态
            List<Status> childStatus = n.getChildStatus();
            //从n的子状态中删除已在open或closed表中出现的状态
            List<Status> statuses = childStatus.stream().filter(status -> {
                return (!open.contains(status) && !closed.contains(status));
            }).map(status -> {
                List<Status> list = new ArrayList<>(n.path);
                status.path = list;
                return status;
            }).collect(Collectors.toList());
            //将n的其余子状态,按生成的次序加入到open表的前端
            open.addAll(statuses);
        }
        System.out.println("搜索的步数:" + closed.size());
    }
}
package com.jn.rz.实验一;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;

/**
* @author 江南大学1033190417
* @date 2022/3/31 11:36
*/
public class Status implements Serializable {

public int[][] status;//状态元素

public Integer depth;

public List<Status> path = new ArrayList<>();//路径

public Status(int[][] status) {
this.status = status;
}

public List<Status> getChildStatus() {
List<Status> childStatus = new ArrayList<>();
if (left()) {
Status s = new Status(copyArray(this.status));
s.depth = this.depth + 1;
childStatus.add(s);
right();
}
if (up()) {
Status s = new Status(copyArray(this.status));
s.depth = this.depth + 1;
childStatus.add(s);
down();
}

if (down()) {
Status s = new Status(copyArray(this.status));
s.depth = this.depth + 1;
childStatus.add(s);
up();
}
if (right()) {
Status s = new Status(copyArray(this.status));
s.depth = this.depth + 1;
childStatus.add(s);
left();
}
return childStatus;
}

//上移动,相对0来说
public boolean up() {
int[] coordinateOf0 = getCoordinateOf0();
int x = coordinateOf0[0];
int y = coordinateOf0[1];
try {
this.status[x][y] = this.status[x - 1][y];
this.status[x - 1][y] = 0;
return true;
} catch (Exception e) {
return false;
}
}

//下移
public boolean down() {
int[] coordinateOf0 = getCoordinateOf0();
int x = coordinateOf0[0];
int y = coordinateOf0[1];
try {
this.status[x][y] = this.status[x + 1][y];
this.status[x + 1][y] = 0;
return true;
} catch (Exception e) {
return false;
}
}

//左移
public boolean left() {
int[] coordinateOf0 = getCoordinateOf0();
int x = coordinateOf0[0];
int y = coordinateOf0[1];
try {
this.status[x][y] = this.status[x][y - 1];
this.status[x][y - 1] = 0;
return true;
} catch (Exception e) {
return false;
}
}

//右移
public boolean right() {
int[] coordinateOf0 = getCoordinateOf0();
int x = coordinateOf0[0];
int y = coordinateOf0[1];
try {
this.status[x][y] = this.status[x][y + 1];
this.status[x][y + 1] = 0;
return true;
} catch (Exception e) {
return false;
}
}

// //得到所有子状态
// public List<Status> getAllChildStatus() {
// List<Status> childStatus = new ArrayList<>();
// if (up()) {
// Status s = new Status(copyArray(this.status));
// childStatus.add(s);
// down();
// }
// if (down()) {
// Status s = new Status(copyArray(this.status));
// childStatus.add(s);
// up();
// }
// if (left()) {
// Status s = new Status(copyArray(this.status));
// childStatus.add(s);
// right();
// }
// if (right()) {
// Status s = new Status(copyArray(this.status));
// childStatus.add(s);
// left();
// }
// return childStatus;
// }

/**
* 定位0的位置
*
* @return 横纵坐标
*/
public int[] getCoordinateOf0() {
for (int i = 0; i < this.status.length; i++) {
for (int j = 0; j < this.status[i].length; j++) {
if (this.status[i][j] == 0) {
return new int[]{i, j};
}
}
}
return new int[]{-1, -1};
}

//深拷贝数组
public static int[][] copyArray(int[][] input) {
int[][] output = new int[input.length][input[0].length];
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
output[i][j] = input[i][j];
}
}
return output;
}


@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Status status1 = (Status) o;
for (int i = 0; i < this.status.length; i++) {
for (int j = 0; j < this.status[i].length; j++) {
if (this.status[i][j] != status1.status[i][j])
return false;
}
}
return true;
}

@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < this.status.length; i++) {
for (int j = 0; j < this.status[i].length; j++) {
result.append(this.status[i][j]).append("\t");
}
result.append("\n");
}
return result.toString();
}

public static void main(String[] args) throws Exception {
int[][] start = new int[3][3];//初始状态
int[][] end = new int[3][3];//目标状态
Stack<Status> open = new Stack<>();//open表
Stack<Status> closed = new Stack<>();//closed表
int depth = 5;//深度限制

FileInputStream fis = new FileInputStream("D:\\桌面\\人工智能\\实验\\src\\com\\jn\\rz\\实验一\\input.txt");
InputStreamReader dis = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(dis);
String s;
int hang = 0;//行号标记
while ((s = reader.readLine()) != null) {
if ("".equals(s))
continue;
if (s.contains("depth")) {
depth = Integer.parseInt(s.split(" ")[1]);
continue;
}
String[] split = s.split(" ");
if (hang >= 3) {
for (int i = 0; i < 3; i++) {
end[hang % 3][i] = Integer.parseInt(split[i]);
}
hang++;
} else {
for (int i = 0; i < 3; i++) {
start[hang % 3][i] = Integer.parseInt(split[i]);
}
hang++;
}
}

Status startStatus = new Status(start);
startStatus.depth = 1;
Status endStatus = new Status(end);
open.add(startStatus);

while (!open.isEmpty()) {
Status n = open.pop();
n.path.add(n);
System.out.println(n);//输出遍历的过程
closed.add(n);
if (n.equals(endStatus)) {
System.out.println("解路长度:"+n.path.size());
System.out.println("找到的解");
for (Status status : n.path) {
System.out.println(status);
}
break;
}
if (n.depth == depth) {
continue;
}
//得到所有子状态
List<Status> childStatus = n.getChildStatus();
//从n的子状态中删除已在open或closed表中出现的状态
List<Status> statuses = childStatus.stream().filter(status -> {
return (!open.contains(status) && !closed.contains(status));
}).map(status -> {
List<Status> list = new ArrayList<>(n.path);
status.path = list;
return status;
}).collect(Collectors.toList());
//将n的其余子状态,按生成的次序加入到open表的前端
open.addAll(statuses);
}
System.out.println("搜索的步数:" + closed.size());
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值