Eight Queens [Java] problem

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;
    }
}

Published 57 original articles · won praise 55 · views 1933

Guess you like

Origin blog.csdn.net/qq_40561126/article/details/104674709