题目是:三横三竖的九宫格里面,填上从1-9九个数,要求每列的和为15,每行的和为15,两条对角线上的数的和为15,而且这九个数没有重复的。在九宫格里输出这九个数。
这是教材上的一个例子,下面是源代码:
[code=Java][/code]
public class J_Grid15
{
int[][] m_board;
J_Grid15()
{
m_board = new int[3][3];
}
private void mb_outputGridRowBoard()
{
int i;
System.out.print("+");
for(i=0; i<5; i++)
{
System.out.print("-");
}
System.out.println("+");
} // 输出九宫格的横段 +-----+
private void mb_outputGridRowBoard(int i)
{
int j;
for(j=0; j < m_board[i].length; j++)
{
System.out.print("|" + m_board[i][j]);
}
System.out.println("|");
} //画九宫格里的小竖线
public void mb_outputGrid()
{
int i;
mb_outputGridRowBoard();
for(i = 0; i < m_board.length; i++)
{
mb_outputGridRowBoard(i);
mb_outputGridRowBoard();
}
} // 输出整个九宫格+九宫格里面的数据
private void mb_dataInit()
{
int i, j, k;
for(i = 0, k = 1; i < m_board.length; i++)
{
for(j = 0; j < m_board[i].length; j++, k++)
{
m_board[i][j] = k;
}
}
} //初始化九宫格:1 2 3
4 5 6
7 8 9
private boolean mb_dataEnd()
{
int i, j, k;
for(i = 0, k = 9; i < m_board.length; i++)
{
for(j = 0; j < m_board[i].length; j++, k--)
{
if(m_board[i][j] != k)
return false;
}
}
return true;
} // 看不懂???
private void mb_dataNext()
{
int i, j;
for(i = m_board.length-1; i >= 0; i--)
{
for(j = m_board[i].length-1; j >= 0; j--)
{
if(m_board[i][j] == 9)
m_board[i][j] = 1;
else
{
m_board[i][j]++;
return;
}
}
}
} //看不懂???
private boolean mb_dataCheckDifferent()
{
int i, j;
int[] digit = new int [10];
for(i = 0; i < m_board.length; i++)
{
for(j = 0; j < m_board[i].length; j++)
{
digit[m_board[i][j]] = 1;
}
}
for(i = 0, j = 0; i < digit.length; i++)
{
j += digit[i];
}
if(j == 9)
return false;
return true;
} // 检查九宫格里的九个数据是否有相同的
private boolean mb_dataCheckSumRow()
{
int i, j, k;
for(i = 0; i < m_board.length; i++)
{
for(j = 0, k = 0; j < m_board[i].length; j++)
{
k += m_board[i][j];
}
if(k != 15)
return false;
}
return true;
} //检查每行的和是否为15
private boolean mb_dataCheckSumColumn()
{
int i, j, k;
for(i = 0; i < m_board.length; i++)
{
for(j = 0, k = 0; j < m_board[i].length; j++)
{
k += m_board[j][i];
}
if(k != 15)
return false;
}
return true;
} //检查每列的和是否为15
private boolean mb_dataCheck()
{
if(mb_dataCheckDifferent())
return false;
if(!mb_dataCheckSumRow())
return false;
if(!mb_dataCheckSumColumn())
return false;
if(m_board[0][0] + m_board[1][1] + m_board[2][2] != 15)
return false;
if(m_board[0][2] + m_board[1][1] + m_board[2][0] != 15)
return false;
return true;
} //检查数据是否合法
public void mb_arrange()
{
int n = 1;
for(mb_dataInit(); !mb_dataEnd(); mb_dataNext())
//判断条件!mb_dataEnd()和mb_dataNext()不是太明白
{
if(mb_dataCheck())
{
System.out.println("The " + n + "th result:");