LeetCode_可以被一步捕獲的棋子數_Array_E

999. 可以被一步捕獲的棋子數

class Solution {
    public int numRookCaptures(char[][] board) {
        if (board == null) {
            return -1;
        }
        int x = 0, y = 0, sum = 0;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'R') {
                    x = i;
                    y = j;
                }
            } 
        }
        int temp = x;        // 上
        while (temp > 0) {
            char c = board[--temp][y];
            if (c == 'p') {
                sum ++;
                break;
            } else if (c == 'B') {
                break;
            }
        }
        temp = x;  // 下
        while (temp < board.length - 1) {
            char c = board[++temp][y];
            if (c == 'p') {
                sum ++;
                break;
            } else if (c == 'B') {
                break;
            }
        }
        temp = y;  // 左
        while (temp > 0) {
            char c = board[x][--temp];
            if (c == 'p') {
                sum ++;
                break;
            } else if (c == 'B') {
                break;
            }
        }
        temp = y;  // 右
        while (temp < board[0].length - 1) {
            char c = board[x][++temp];
            if (c == 'p') {
                sum ++;
                break;
            } else if (c == 'B') {
                break;
            }
        }
        return sum;
    }
}

方向數組:

class Solution {
    public int numRookCaptures(char[][] board) {
        // 方向數組   上下左右
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        int x = 0, y = 0;       // 找R的位置
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'R') {
                    x = i;
                    y = j;
                    break;
                }
            }
        }
        int sum = 0;        //計算有幾個
        for (int i = 0; i < 4; i++) {   
            int X = x, Y = y;
            while (true) {
                X += dx[i];
                Y += dy[i];
                if (X < 0 || X >= board.length || Y < 0 || Y >= board[0].length || board[X][Y] == 'B') {
                    break;
                } else if (board[X][Y] == 'p') {
                    sum++;
                    break;
                }
            }
        }
        return sum;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章