hud 5547 sodoku (DFS)
题目大意:4*4的网格做数独,*代表空的格子,要求将4*4分解为4个2*2的网格,每个2*2网格也满足数独(包含1234)
code:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int cnt[4]; bool vis[4][5]; char m[4][4]; bool dfs(int x,int y){ int nx,ny; nx = x/2; ny = y/2; if(x > 3){ return true; } if(m[x][y] != '*'){ if((x == 1 && y == 1) || (x == 1 && y == 3) ||(x == 3 && y == 1)||(x == 3 && y == 3)){ if(m[0+2*nx][0+2*ny] + m[1+2*nx][1+2*ny] + m[1+2*nx][0+2*ny] + m[0+2*nx][1+2*ny] != 10 + 4 * '0' ){ return false; } else{ if(m[0+2*nx][0+2*ny] == m[1+2*nx][1+2*ny] || m[1+2*nx][0+2*ny] == m[0+2*nx][1+2*ny]) return false; } } if(y + 1 < 4) return dfs(x,y+1); else return dfs(x+1,0); } else if(m[x][y] == '*'){ for(int i = 1;i <= 4;i ++){ int flag = 1; m[x][y] = i + '0'; for(int j = 0;j < 4;j ++){ if(j == y) continue; if(m[x][j] - '0' == i) {flag = 0;break;} } for(int j = 0;j < 4;j ++){ if(x == j) continue; if(m[j][y] - '0' == i) {flag = 0;break;} } if((x == 1 && y == 1) || (x == 1 && y == 3) ||(x == 3 && y == 1)||(x == 3 && y == 3)){ if(m[0+2*nx][0+2*ny] + m[1+2*nx][1+2*ny] + m[1+2*nx][0+2*ny] + m[0+2*nx][1+2*ny] != 10 + 4 * '0'){ flag = 0; } else{ if(m[0+2*nx][0+2*ny] == m[1+2*nx][1+2*ny] || m[1+2*nx][0+2*ny] == m[0+2*nx][1+2*ny]) flag = 0; } } if(flag){ m[x][y] = i + '0'; if(y + 1 < 4) { if(dfs(x,y+1)) return true; } else { if(dfs(x+1,0)) return true; } } m[x][y] = '*'; } return false; } } int main() { int cas; cin >> cas; getchar(); int cnt = 1; while(cas --){ for(int i = 0;i < 4;i ++){ for(int j = 0;j < 4;j ++){ cin >> m[i][j]; } getchar(); } dfs(0,0); printf("Case #%d:\n",cnt++); for(int i = 0;i < 4;i ++){ for(int j = 0;j < 4;j ++){ cout << m[i][j]; } cout << endl; } } return 0; }
posted on 2016-07-27 09:41 Tob's_the_top 阅读(127) 评论(0) 编辑 收藏 举报