import java.util.Scanner;
public class Chi {
static int[][] board = new int[19][19];
static boolean[][] gone = new boolean[19][19];
static boolean[][] isCount = new boolean[19][19];
static int chessColor;
static int chiNum = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int x, y;
try {
System.out.println("請輸入棋盤:");
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[i].length; j++)
board[i][j] = sc.nextInt();
}
System.out.print("請輸入座標: ");
x = sc.nextInt();
y = sc.nextInt();
} finally {
sc.close();
}
if (board[x][y] == 0)
System.out.println("這個座標沒有任何棋子");
else {
chessColor = board[x][y];
countChi(x, y);
if (chessColor == 1)
System.out.println("您算的是黑子的氣");
else
System.out.println("您算的是白子的氣");
System.out.println("共有" + chiNum + "個氣");
}
}
private static void countChi(int x, int y) {
if (board[x][y] == 0 && !isCount[x][y]) {
chiNum++;
isCount[x][y] = true;
}
else if (!gone[x][y] && board[x][y] == chessColor) {
gone[x][y] = true;
countChi(x - 1, y);
countChi(x, y - 1);
countChi(x, y + 1);
countChi(x + 1, y);
gone[x][y] = false;
}
}
}
範例輸入輸出:
這是老師出的額外題目,題目的要求是輸入一個棋盤,並且指定一個座標,並算出指定座標棋子所在區域的氣。此程式會自動辨識您指定的座標是黑子區域還是白子區域,若您指定黑子就會為您算出黑子的氣;若您指定白子就會為您算出白子的氣,若您指定的地方沒有任何棋子,程式會告訴您這地方沒有任何棋子。此程式的作法就是不斷地搜尋這區域周圍的氣(也就是沒有任何棋子的地方),若已經搜尋過得地方用gone這個布林陣列把它記起來,以避免無限的搜尋,若找到氣了,就把氣數+1然後用布林陣列記住這個地方已經算過氣了,避免未來再重複算一次。
此程式的輸入為一個19 * 19的棋盤,0代表沒有棋子, 1代表黑棋, 2代表白棋,完成後程式會要求您輸入一個座標,格式為(x y),x和y的範圍皆為0~18。輸出為你算的是什麼棋子的氣,以及總共是多少氣。




