U E D R , A S I H C RSS

Eight Queen Problem/안혁준

package main

import "fmt";

func main(){
	var chess Chess;

	chess.solve(0);
	chess.print();
}

type Chess struct {
	queenPos [8]int;
}
func (chess * Chess) check(x int, y int) bool {
	for i := 0; i < x; i++ {
		//verticle
		if chess.queenPos[i] == y{
			return false;
		}

		diff := x - i;
		if chess.queenPos[i] == y - diff {
			return false;
		}
		if chess.queenPos[i] == y + diff {
			return false;
		}
	}
	return true;
}
func (chess * Chess) putQueen(x int, y int) {
	chess.queenPos[x] = y;
}
func (chess * Chess) print(){
	for i := 0; i < 8; i++ {
		for j := 0; j < 8; j++ {
			if chess.queenPos[i] == j{
				fmt.Printf("Q");
			} else {
				fmt.Printf("-");
			}
		}
		fmt.Printf("\n");
	}
}
func (chess * Chess) solve(row int) bool{
	if row >= 8 {
		return true;
	}
	for i := 0; i < 8; i++ {
		if chess.check(row, i) {
			chess.putQueen(row, i);
			if chess.solve(row + 1) {
				return true;
			}
		}
	}
	return false;
}


Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:23:12
Processing time 0.0094 sec