您的位置:首页 > 职场人生

程序员面试金典——解题总结: 9.17中等难题 17.2判断井字游戏中某个玩家是否赢了游戏

2017-01-16 00:13 323 查看
#include <iostream>
#include <stdio.h>
#include <vector>

using namespace std;

/*
问题:设计一个算法,判断玩家是否赢了井字游戏
分析:首先井字游戏是跟五子棋类似,任意连线上有三个子就算成功
现在是判断某个玩家是否赢了游戏。
赢:
1) 任意一行3个连续的子
2)      列
3)      斜线
最简单的方法就是:每次轮到某个棋手落子后,判断该棋手棋子的颜色,以及该棋子所在行,或所在列,或所在斜线(如果有的话),是否有三个和它颜色相同
的棋子
时间复杂度:每个棋子都需要判断遍历2行到3行,设棋盘长宽为n*m,所以时间复杂度为: O(n*m*m) = o(n*m^2)接近O(n^2)这种

输入:
3(棋盘的宽度) 3(棋盘的高度)

关键:
1 棋子除了黑白两种颜色外,注意要设置空,
*/
const int MAXSIZE = 1000;
//需要定义棋子这个对象,包含颜色,横纵坐标。颜色中为空,表示该棋子还没有落下
enum Color{EMPTY , WHITE , BLACK};
typedef struct Chessman
{
int _x;
int _y;
Color _color;
}Chessman;

//输入参数为当前棋子,棋盘的宽和高,棋盘矩阵,赢所需要的棋子个数
bool isWin(Chessman& chessman, int width , int height , vector< vector<Chessman> >& chessBoard , int winNum)
{
int x = chessman._x;
int y = chessman._y;
Color color = chessman._color;
//检查所在行是否有3个同样颜色的棋子
int count = 0;
for(int i = y ; i < width ; i++)
{
//如果出现了不同的颜色,需要,直接退出
if( chessBoard.at(x).at(i)._color != color)
{
break;
}
count++;
}
for(int i = y - 1 ; i >= 0 ; i--)
{
//如果出现了不同的颜色,需要,直接退出
if( chessBoard.at(x).at(i)._color != color)
{
break;
}
count++;
}
if(count < winNum)
{
return false;
}

//检索所在列是否有3个同样地棋子
count = 0;
for(int i = x ; i < height;  i++)
{
if( chessBoard.at(i).at(y)._color != color)
{
break;
}
count++;
}
for(int i = x - 1 ; i >= 0 ; i++ )
{
if( chessBoard.at(i).at(y)._color != color)
{
break;
}
count++;
}
if(count < winNum)
{
return false;
}

//判断所在斜线是否连成一行
count = 0;
int tempX = x , tempY = y;
while( tempX < height && tempY < width )
{
if( chessBoard.at(tempX).at(tempY)._color != color )
{
break;
}
count++;
tempX++;
tempY++;
}
tempX = x - 1 ;
tempY = y - 1;
while(tempX >= 0 && tempY >= 0)
{
if( chessBoard.at(tempX).at(tempY)._color != color )
{
break;
}
count++;
tempX--;
tempY--;
}
if(count < winNum)
{
return false;
}
return true;
}

int main(int argc , char* argv[])
{
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐