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

#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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值