《Cracking the Coding Interview》——第17章:普通题——题目2

2014-04-28 22:05

题目:写个程序判断三连棋哪一方赢了。

解法:三个相同的棋子连成一条横线,竖线或者对角线就判断为赢了。

代码:

 1 // 17.2 Write an algorithm to check if someone has won the tic-tac-toe game.

 2 // Here is the game:

 3 //    xo-

 4 //    ox-

 5 //    --x

 6 // 'x' won the game.

 7 // Rule: anyone who gets three consecutive pieces in a row, a column or a diagonal line first wins.

 8 #include <cstdio>

 9 using namespace std;

10 

11 int check(int a[][3])

12 {

13     if (a == nullptr) {

14         return -1;

15     }

16     

17     int i;

18     for (i = 0; i < 3; ++i) {

19         if (a[i][0] == a[i][1] && a[i][1] == a[i][2] && a[i][2] != 0) {

20             return a[i][2];

21         }

22         if (a[0][i] == a[1][i] && a[1][i] == a[2][i] && a[2][i] != 0) {

23             return a[i][2];

24         }

25     }

26     if (a[0][0] == a[1][1] && a[1][1] == a[2][2] && a[2][2] != 0) {

27         return a[2][2];

28     }

29     if (a[0][2] == a[1][1] && a[1][1] == a[2][0] && a[2][0] != 0) {

30         return a[2][2];

31     }

32     

33     return 0;

34 }

35 

36 int main()

37 {

38     int a[3][3];

39     int i, j;

40     

41     for (i = 0; i < 3; ++i) {

42         for (j = 0; j < 3; ++j) {

43             scanf("%d", &a[i][j]);

44         }

45     }

46     printf("%d\n", check(a));

47     

48     return 0;

49 }

 

你可能感兴趣的:(interview)