fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. const int dx[] = {-1, 0, +1, 0};
  9. const int dy[] = {0, -1, 0, +1};
  10. bool dfs(vector<string> &f, int n, int r, int c, int m)
  11. {
  12. const int rows = f.size();
  13. const int cols = f[0].size();
  14. if (m == n) {
  15. return true;
  16. }
  17. for (int k = 0; k < 4; ++k) {
  18. int r2 = r + dy[k];
  19. int c2 = c + dx[k];
  20. if (r2 < 0 || rows <= r2 || c2 < 0 || cols < c2) {
  21. continue;
  22. }
  23. if (f[r2][c2] != '0') {
  24. continue;
  25. }
  26. f[r2][c2] = '2';
  27. if (dfs(f, n, r2, c2, m + 1)) {
  28. return true;
  29. }
  30. f[r2][c2] = '0';
  31. }
  32. return false;
  33. }
  34.  
  35. int main()
  36. {
  37. int rows, cols;
  38. while (cin >> rows >> cols) {
  39. vector<string> f(rows);
  40. for (auto &s : f) {
  41. cin >> s;
  42. cout << s << endl;
  43. }
  44. int n = 0;
  45. int sr = -1, sc = -1;
  46. for (int i = 0; i < rows; ++i) {
  47. for (int j = 0; j < cols; ++j) {
  48. if (f[i][j] == '0') {
  49. ++n;
  50. }
  51. if (f[i][j] == '2') {
  52. sr = i;
  53. sc = j;
  54. }
  55. }
  56. }
  57. if (dfs(f, n, sr, sc, 0)) {
  58. cout << "OK" << endl;
  59. } else {
  60. cout << "NG" << endl;
  61. }
  62. cout << endl;
  63. }
  64. }
  65.  
Success #stdin #stdout 0.01s 5504KB
stdin
4 4
0000
0210
0000
0100

4 4
0000
0200
0010
0000

5 6
000000
210000
000100
000001
000000

5 6
000000
210000
000100
000000
000001
stdout
0000
0210
0000
0100
OK

0000
0200
0010
0000
NG

000000
210000
000100
000001
000000
OK

000000
210000
000100
000000
000001
NG