|
题目描述:牛妹在和牛牛下牛客象棋。现在轮到牛妹了,牛妹想知道她在这一回合能否战胜牛牛。
棋盘chessboard上只可能包含:炮,将,车,兵
牛客象棋的规则解释:
炮:炮在不吃子的时候,走动与车完全相同,但炮在吃棋子时,必须跳过一个棋子,我方的和敌方的都可以
兵:可以上下左右移动,每次只能移动一格
车:上下左右均可走,只要无棋子阻拦,步数不受限制。
将:可以上下左右移动,每次只能移动一格
接下来给出一个棋盘,牛妹的棋子用大写字母表示,牛牛的棋子用小写字母表示。
将用J,j表示,炮用P,p表示,车用C,c表示,兵用B,b表示,没有棋子的格子用.表示
保证棋盘上一定同时包含J与j各一个。
输入:
给定chessboard数组
6≤chessboard.size≤10^3
6≤chessboard[i].length≤10^3
输出:
牛妹能胜利则返回"Happy",否则返回"Sad"
示例1
输入:["......",
"..B...",
"P.C.j.",
"......",
"..b...",
" ...J.." ]
输出:"Happy"
说明:牛妹的炮可以攻击到牛牛的将,所以获胜
代码实现(by quality丶6):
import java.util.*;
public class Solution {
/**
*
* @param chessboard string字符串一维数组
* @return string字符串
*/
public String playchess (String[] chessboard) {
int len = chessboard.length;
char[][] a = new char[len][];
int j = 0;
int k = 0;
for(int i = 0; i < len; i++) {
char [] c = chessboard[i].toCharArray();
if(chessboard[i].indexOf("j") > -1) {
j = chessboard[i].indexOf("j");
k = i;
}
a[i] = c;
}
int ot = 0;
for(int i = k - 1; i >= 0; i--) {//向上
if(i == k - 1 && (a[i][j] == 'B' || a[i][j] == 'J')) {
return "Happy";
}else if(ot == 0 && a[i][j] == 'C') {
return "Happy";
}else if(ot == 1 && a[i][j] == 'P') {
return "Happy";
}else if(ot == 0 && a[i][j] != '.') {
ot ++;
}else if(ot > 1) {
break;
}
}
ot = 0;
for(int i = k + 1; i < len; i++) {//向下
if(i == k + 1 && (a[i][j] == 'B' || a[i][j] == 'J')) {
return "Happy";
}else if(ot == 0 && a[i][j] == 'C') {
return "Happy";
}else if(ot == 1 && a[i][j] == 'P') {
return "Happy";
}else if(ot == 0 && a[i][j] != '.') {
ot ++;
}else if(ot > 1) {
break;
}
}
ot = 0;
for(int i = j - 1; i >= 0; i--) {//向左
if(i == j - 1 && (a[k][i] == 'B' || a[k][i] == 'J')) {
return "Happy";
}else if(ot == 0 && a[k][i] == 'C') {
return "Happy";
}else if(ot == 1 && a[k][i] == 'P') {
return "Happy";
}else if(ot == 0 && a[k][i] != '.') {
ot ++;
}else if(ot > 1) {
ot = 0;
break;
}
}
ot = 0;
for(int i = j + 1; i < a[k].length; i++) {//向右
if(i == j + 1 && (a[k][i] == 'B' || a[k][i] == 'J')) {
return "Happy";
}else if(ot == 0 && a[k][i] == 'C') {
return "Happy";
}else if(ot == 1 && a[k][i] == 'P') {
return "Happy";
}else if(ot == 0 && a[k][i] != '.') {
ot ++;
}else if(ot > 1) {
break;
}
}
return "Sad";
}
}
|
|