连珠算法

最近去面试 其中有一个面试题是关于连珠算法的

2There are two players to play a game with 4x4 positions. Each player can take one position for his turn. The winner is the first one to take all of four positions in one line. 

The figure shows three winning cases. 

Let’s make a simple application to make the judgment which player wins a game.

  连珠算法

以下是我写的代码

代码
         ///   <summary>
        
///  从当前坐标读取那方胜
        
///   </summary>
        
///   <param name="status"> White or Black </param>
         public   bool  IsWins( int  x, int  y,Status status)
        {
            
int  chessX,chessY;
            
int  sum  =   1 ;

            
// 往四个方向读取玩家旗子状态
             for  ( int  i = 0 ;i < 4 ;i ++ )
            {
                chessX 
=  x  +  dir[i].x;
                chessY 
=  y  +  dir[i].y;

                
while  (chessX  <  m_ChessSize  &&  chessX  >=   0   &&  chessY  <  m_ChessSize  &&  chessY  >=   0   &&  m_Chessboard[chessX, chessY]  ==  (( int )status))
                {
                    sum
++ ;
                    
if  (sum  ==   4 )
                        
return   true ;
                    chessX 
+=  dir[i].x;
                    chessY 
+=  dir[i].y;
                }

                
// 反向读取
                chessX  =  x  -  dir[i].x;
                chessY 
=  y  -  dir[i].y;
                
while  (chessX  <  m_ChessSize  &&  chessX  >=   0   &&  chessY  <  m_ChessSize  &&  chessY  >= 0   &&  m_Chessboard[chessX, chessY]  ==  (( int )status))
                {
                    sum
++ ;
                    
if  (sum  ==   4 )
                        
return   true ;
                    chessX 
-=  dir[i].x;
                    chessY 
-=  dir[i].y;
                }
                
// 单方向不成立 清空计数器
                sum  =   1 ;
            }
            
return   false ;
        }

 不知大家有没有更好的算法

完整工程下载

你可能感兴趣的:(算法)