publicint[] fraction(int[] cont) { int up = 1, down = cont[cont.length-1]; int temp; for(int i = cont.length-2; i >=0 ; i--){ up += down*cont[i]; temp = up; up = down; down = temp; }
publicstaticbooleanrobot(String command, int[][] obstacles, int x, int y){ char[] cmd = command.toCharArray(); int r = 0, u = 0; //String转化为char[]数组容易遍历 for (char c : cmd) { if (c == 'U') u++; else r++; }
if (!reach(r, u, x, y, cmd)) returnfalse;
//逻辑上删除在目标后面的障碍 int index = 0; for (int i = 0; i < obstacles.length; i++) if (obstacles[i][0] <= x && obstacles[i][1] <= y) { obstacles[index][0] = obstacles[i][0]; obstacles[index][1] = obstacles[i][1]; index++; } //判断目标前面的障碍是否在路径上 for (int i = 0; i < index; i++){ if (reach(r, u, obstacles[i][0], obstacles[i][1], cmd)) returnfalse; }
returntrue; }
publicstaticbooleanreach(int r, int u, int x, int y, char[] cmd){ //求出最小的循环次数 int i = Math.min(x/r,y/u); int nx = i*r, ny = i*u;
for (char c : cmd){ if (nx == x && ny == y) returntrue; if(c == 'U') ny+=1; else nx+=1; } returnfalse; }
publicintdomino(int n, int m, int[][] broken){ if (broken.length == 0 ){//棋盘无坏点,直接返回 棋盘个数/2 return n * m >> 1; }
board = newboolean[n][m]; for(boolean[] i : board){//棋盘全部初始化为true Arrays.fill(i,true); } for(int[] i : broken){//坏点设为false board[i[0]][i[1]] = false; }
return hungary(); }
privateinthungary(){//匈牙利算法,返回最大匹配数 int maxOfMatch = 0; int n = board.length, m = board[0].length; visit = newboolean[n*m];//用一维数组存储二维数组 link = newint[n*m]; Arrays.fill(link, -1);
for (int r = 0; r < n; r++) {//遍历v1中的点 for (int c = ((r&1) == 0 ? 0 : 1); c < m; c+=2){//让遍历的点不相邻 if (board[r][c]){ Arrays.fill(visit,false); if (find(r,c)){ maxOfMatch++; } } } }
return maxOfMatch; }
privatebooleanfind(int row, int col){ int n = board.length, m = board[0].length; for (int[] d : dir){ int r = row + d[0]; int c = col + d[1];
if(r < 0 || c < 0 || r >= n || c >= m){//越界 continue; }
int v2 = r * m + c; if (board [r] [c] && !visit[v2]){ visit[v2] = true; if (link[v2] == -1 || find(link[v2]/m, link[v2]%m)){//因为link是用一维数组存储二维数组 link[v2] = row * m + col; //因此row = link[v2]/m, col = lin[v2]%m,由左式可知 returntrue; } } }