标签:interview
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) }
标签:interview
原文地址:http://7371901.blog.51cto.com/7361901/1588264