1. Problem description:
Suppose there are only two pieces on the Chinese chess board: "Jiang" and "Shuai.
Write out all possible legal positions of "" and "" based on the rules of chess.
Only one variable must be declared.
2. Modeling
It can be seen from the layout on the board that the moving range of "" and "" is 3 × 3.
.
1--2--3
|
4--5--6
|
7--8--9
The above model simulates all possible positions of "" or "", because "" and ""
It cannot be in the same column at the same time, so when "place" at, 7, "handsome" is. And vice versa.
The following uses a to represent "yes" and B to represent "handsome" for simulation.
Public class chess {</P> <p>/** <br/> * method 1 <br/> */<br/> Public static void solutiona () {<br/> // contains non-compliant rules. A total of 81 conditions exist. <br/> int icount = 81; <br/> while (-- icount> 0) <br/> // icount/9% 3 indicates the column <br/> // icount % 9% 3 indicates the row <br/> If (icount/9% 3! = Icount % 9% 3) <br/> // output information that complies with the rules <br/> system. out. println ("A =" + (icount/9 + 1) + "B =" + (icount % 9 + 1 )); <br/>}< br/>/** <br/> * method 2 <br/> */<br/> Public static void solutionb () {<br/> // define a class as a variable, in C, you can use struct to represent <br/> class position {<br/> // the position of a <br/> Public int; <br/> // location of B <br/> Public int B; <br/>}< br/> // declare a variable <br/> position P = new position (); <br/> for (P. a = 1; p. A <= 9; p. A ++) <br/> for (P. B = 1; p. B <= 9; p. B ++) <br/> If (P. A % 3! = P. B % 3) <br/> system. out. println ("A =" + P. A + "B =" + P. B ); <br/>}< br/>/** <br/> * test <br/> */<br/> Public static void main (string [] ARGs) {<br/> // test method A <br/> system. out. println ("======= first method ======"); <br/> chess. solutiona (); <br/> // Test Method B <br/> system. out. println ("======= second method ======"); <br/> chess. solutionb (); <br/>}< br/>}
This problem andAlgorithmFrom the beauty of programming.