NIM(3), Java

public class NIM {

public static void main(String[] args) {
System.out.println(nim(8, 6));
}

public static Result nim(int m, int n) {
if (m == n || m == 0 || n == 0) {
return new Result(true, m, n);
}
if (m < n) {
int tmp = m;
m = n;
n = tmp;
}
Result[][] matrix = new Result[m][n];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < m; j++) {
if (matrix[j][i] == null) {
propagateFalseResult(m, n, j, i, matrix);
if (matrix[m - 1][n - 1] != null) {
return matrix[m - 1][n - 1];
}
}
}
}
return matrix[m - 1][n - 1];
}

private static void propagateFalseResult(int m, int n, int x, int y, Result[][] matrix) {
matrix[x][y] = new Result(false, x + 1, y + 1);
Result tResult = new Result(true, x + 1, y + 1);
for (int i = y + 1; i < n; i++) {
matrix[x][i] = tResult;
}
for (int i = x + 1; i < m; i++) {
matrix[i][y] = tResult;
}
int steps = m - x;
if (steps > n - y) {
steps = n - y;
}
for (int i = 1; i < steps; i++) {
matrix[x + i][y + i] = tResult;
}
if (x < n) {
for (int i = x + 1; i < m; i++) {
matrix[i][x] = tResult;
}
}

printMatrix(matrix);

}

private static void printMatrix(Result[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%-15s", matrix[i][j]);
}
System.out.println();
}
System.out.println();
}
}

class Result {

public String toString() {
return state + " (" + x + ", " + y + ")";
}

public Result(boolean s, int x, int y) {
state = s;
this.x = x;
this.y = y;
}

public boolean state;
public int x, y;
}


[table]
|null|null|null|null|null|null|
|false (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
|true (2, 1)|true (2, 1)|true (2, 1)|null|null|null|
|true (2, 1)|true (2, 1)|null|true (2, 1)|null|null|
|true (2, 1)|true (2, 1)|null|null|true (2, 1)|null|
|true (2, 1)|true (2, 1)|null|null|null|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
[/table]

[table]
|null|null|null|null|null|null|
|false (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|true (2, 1)|
|true (2, 1)|true (2, 1)|null|null|null|null|
|true (2, 1)|true (2, 1)|true (2, 1)|null|null|null|
|true (2, 1)|true (2, 1)|false (5, 3)|true (5, 3)|true (5, 3)|true (5, 3)|
|true (2, 1)|true (2, 1)|true (5, 3)|true (5, 3)|true (5, 3)|null|
|true (2, 1)|true (2, 1)|true (5, 3)|null|true (5, 3)|true (2, 1)|
|true (2, 1)|true (2, 1)|true (5, 3)|null|true (5, 3)|true (5, 3)|
[/table]

true (5, 3)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值