QQ群里面一个朋友说的一个面试题,本人比较笨,折腾了两个小时才弄出来,贴上来纪念一下:
public class TestSaoLei {
private static int row = 11;
private static int col = 12;
private static int num = 50;
private static String strBomb = "B";
private static String strNo = "0";
private static String[][] bombMap = new String[row][col];
public static void main(String[] args){
TestSaoLei tBomb = new TestSaoLei();
tBomb.setClearBombMap();
}
/**
* 设置扫雷地图
*
*/
public void setClearBombMap(){
//初始化
for(int i = 0;i < bombMap.length;i++){
for(int j = 0;j < bombMap[i].length;j++){
bombMap[i][j] = strNo;
}
}
//布雷
setBombPlace();
//计算周围雷的数量
setBombNumPlace();
//打印雷图
System.out.print("/n/n");
for(int i = 0;i < bombMap.length;i++){
for(int j = 0;j < bombMap[i].length;j++){
System.out.print(bombMap[i][j] + " ");
}
System.out.print("/n");
}
}
/**
* 布雷
* @return
*/
private void setBombPlace(){
String strPlace = ";";
System.out.println("雷点的坐标:");
// 随机生成雷的位置
for(int m = 0,n = num;m < n;m++){
int leiPlace = (int)(Math.random() * (row * col));
//如果存在相同位置多做一次循环
if(strPlace.indexOf(";" + leiPlace + ";") > -1){
n++;
continue;
}else{
int rowNum = leiPlace / col;
int colNum = leiPlace % col;
bombMap[rowNum][colNum] = strBomb;
System.out.print("[" + rowNum + "," + colNum + "],");
strPlace += leiPlace + ";";
}
}
}
/**
* 计算雷的数量
*
*/
private void setBombNumPlace(){
String curPalce = "",leftPlace = "",rightPlace = "",upPlace = "",downPlace = "";
String upLeftPlace = "",upRightPlace = "",downLeftPlace = "",downRightPlace = "";
for(int i = 0;i < bombMap.length;i++){
for(int j = 0;j < bombMap[i].length;j++){
curPalce = bombMap[i][j];
int leiNum = 0;
//如果当前位置不是雷则处理
if(!curPalce.equals(strBomb)){
if(i - 1 > 0){
upPlace = bombMap[i-1][j];
if(upPlace.equals(strBomb)){
leiNum++;
}
}
if(i + 1 < row){
downPlace = bombMap[i+1][j];
if(downPlace.equals(strBomb)){
leiNum++;
}
}
if(j - 1 > 0){
leftPlace = bombMap[i][j-1];
if(leftPlace.equals(strBomb)){
leiNum++;
}
}
if(j + 1 < col){
rightPlace = bombMap[i][j+1];
if(rightPlace.equals(strBomb)){
leiNum++;
}
}
if(i - 1 > 0 && j - 1 > 0){
upLeftPlace = bombMap[i-1][j-1];
if(upLeftPlace.equals(strBomb)){
leiNum++;
}
}
if(i - 1 > 0 && j + 1 < col){
upRightPlace = bombMap[i-1][j+1];
if(upRightPlace.equals(strBomb)){
leiNum++;
}
}
if(i + 1 < row && j - 1 > 0){
downLeftPlace = bombMap[i+1][j-1];
if(downLeftPlace.equals(strBomb)){
leiNum++;
}
}
if(i + 1 < row && j + 1 < col){
downRightPlace = bombMap[i+1][j+1];
if(downRightPlace.equals(strBomb)){
leiNum++;
}
}
bombMap[i][j] = String.valueOf(leiNum);
}
}
}
}
}