天天看點

[Java]八皇後問題

package tree;

import java.util.LinkedList;

public class Four {
    static int n = 8;
    static LinkedList<Location> res = new LinkedList<>();
    public static void four (int i) {
        if (i >= n) {
            show();
        } else {
            for (int j = 0; j < n; j ++) {
                boolean flag = true;
                for (Location l : res) {
                    if (l.i == i || l.j == j || l.i + l.j == i + j || l.i - l.j == i - j) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    res.push(new Location(i,j));
                    four(i + 1);
                    res.pop();
                }
            }
        }
    }
    public static void show () {
        for (Location l : res) {
            System.out.print("(" + l.i + "," + l.j + ")");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        four(0);
    }
}
class Location {
    int i,j;
    public Location(int i,int j) {
        this.i = i;
        this.j = j;
    }
}

           

繼續閱讀