首页 > 代码库 > CC150 19.2
CC150 19.2
19.2 Design an algorithm to figure out if someone has won in a game of tic-tac-toe.
class TicTacToe { enum Tic { X, O } // Given TicTacToe map, wheter t has won the game. // Assume map is a not-null 3*3 matrix, containing no null elements. // // check row, check column, check corner // This is a brute force solution. boolean checkRow(T[][] map, int r, T t) { for (int i = 0 ; i < 3 ; i ++) { if (map[r][i] != t) return false; } return true; } boolean checkColumn(T[][] map, int c, T t) { for (int i = 0 ; i < 3 ; i ++) { if (map[i][r] != t) return false; } return true; } boolean checkCornerLeft(T[][] map, T t) { for (int i = 0 ; i < 3 ; i ++) { if (map[i][i] != t) return false; } return true; } boolean checkCornerRight(T[][] map, T t) { for (int i = 0 ; i < 3 ; i ++) { if (map[2 - i][i] != t) return false; } return true; } boolean won(T[][] map, T t) { // Only check first row and first column for (int i = 0 ; i < 3 ; i ++) { if (checkRow(map, i, t)) return true; if (checkColumn(map, i, t)) return true; } checkCornerLeft(map, t); checkCornerRight(map, t); return false; } // A second option is that. // There is 9 positions, each position has 2 choices. // Thus, totally there are 2^9 conditions. // Use bit map to represents these 2^9. // If won, mark it as 1. // Check some one won‘ only needs O(1) }
CC150 19.2
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。