fork(5) download
  1. #include <cstdio>
  2. #include <string>
  3. #include <queue>
  4. #include <map>
  5. using namespace std;
  6.  
  7. int N;
  8.  
  9. void fill(string& s, int r, int c, int change, int color) {
  10. s[r * N + c] = color;
  11. if (r + 1 < N && s[(r + 1) * N + c] == change) fill(s, r + 1, c, change, color);
  12. if (c + 1 < N && s[r * N + c + 1] == change) fill(s, r, c + 1, change, color);
  13. if (r && s[(r - 1) * N + c] == change) fill(s, r - 1, c, change, color);
  14. if (c && s[r * N + c - 1] == change) fill(s, r, c - 1, change, color);
  15. }
  16.  
  17. bool check(string& s) {
  18. for (int i = 1; i < N * N; i++)
  19. if (s[i] != s[0]) return 0;
  20. return 1;
  21. }
  22.  
  23. int main() {
  24. while (scanf("%d", &N) && N) {
  25. int i, tmp, max = 0;
  26. string source;
  27. for (i = 0; i < N * N; i++) {
  28. scanf("%d", &tmp);
  29. max = tmp > max ? tmp : max;
  30. source.insert(source.end(), tmp + '0');
  31. }
  32. if (check(source)) {
  33. puts("0");
  34. continue;
  35. }
  36. queue<string> q;
  37. map<string, int> dis;
  38. q.push(source);
  39. dis[source] = 0;
  40. bool find = 0;
  41. while (!q.empty() && !find) {
  42. string now = q.front();
  43. int d = dis[now];
  44. q.pop();
  45. for (int color = '0'; color <= max + '0'; color++) {
  46. if (color == now[0]) continue;
  47. string next = now;
  48. fill(next, 0, 0, now[0], color);
  49. if (check(next)) {
  50. printf("%d\n", d + 1);
  51. find = 1;
  52. break;
  53. }
  54. if (!dis.count(next)) {
  55. q.push(next);
  56. dis[next] = d + 1;
  57. }
  58. }
  59. }
  60. }
  61. return 0;
  62. }
  63.  
Success #stdin #stdout 2.54s 37192KB
stdin
2 
0 0  
0 0 
3 
0 1 2 
1 1 2 
2 2 1 
4
1 0 2 0
1 2 0 3
2 0 3 4
5 1 1 4
7
0 1 2 3 4 5 4
4 5 4 3 2 1 4
0 1 2 3 4 5 4
4 5 4 3 2 1 4
0 1 2 3 4 5 4
4 5 4 3 2 1 0
0 1 2 3 4 5 4
7
0 1 2 3 4 5 4
4 5 4 3 2 1 0
0 1 2 3 4 5 4
4 5 4 3 2 1 0
0 1 2 3 4 5 4
4 5 4 3 2 1 0
0 1 2 3 4 5 4
8
0 1 2 3 4 5 4 3
3 4 5 4 3 2 1 0
0 1 2 3 4 5 4 3
3 4 5 4 3 2 1 0
0 1 2 3 4 5 4 3
3 4 5 4 3 2 1 0
0 1 2 3 4 5 4 3
3 4 5 4 3 2 1 0
0
stdout
0
3
7
8
8
16