結果
問題 | No.86 TVザッピング(2) |
ユーザー |
![]() |
提出日時 | 2014-12-05 01:45:05 |
言語 | C++11(廃止可能性あり) (gcc 13.3.0) |
結果 |
AC
|
実行時間 | 2,264 ms / 5,000 ms |
コード長 | 2,715 bytes |
コンパイル時間 | 841 ms |
コンパイル使用メモリ | 85,948 KB |
実行使用メモリ | 7,848 KB |
最終ジャッジ日時 | 2025-06-20 13:57:28 |
合計ジャッジ時間 | 4,359 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 3 |
other | AC * 30 |
ソースコード
#include <iostream> #include <vector> #include <cstdio> #include <sstream> #include <map> #include <string> #include <algorithm> #include <queue> #include <cmath> using namespace std; //l b r u int x[] = {-1,0,1,0}; int y[] = {0,1,0,-1}; int dfs(vector<vector<int> > &G, vector<bool> &visit, int pos){ visit[pos] = true; int ret = 1; for(int i=0; i<G[pos].size(); i++){ int next = G[pos][i]; if(visit[next]) continue; ret += dfs(G, visit, next); } return ret; } int dfs_(vector<string> &G, int n, int m, vector<bool> &visit, int pos, int start, int toward){ visit[pos] = true; int ret = 1; //進めるだけ進む //すでに訪れた点にぶつかるとそこで止まる。 int xx = pos%m + x[toward]; int yy = pos/m + y[toward]; while(xx>=0 && xx < m && yy>=0 && yy < n){ if(G[yy][xx]=='.' && !visit[xx+yy*m]){ pos = xx + yy*m; visit[pos] = true; ret++; xx = pos%m + x[toward]; yy = pos/m + y[toward]; }else{ break; } } //次がstart地点なら終了 if(xx+yy*m == start){ return ret; } //今いる場所から左に曲がる int next_x = pos%m + x[(toward+3)%4]; int next_y = pos/m + y[(toward+3)%4]; int next = next_x + next_y*m; //曲がった先の場所に進めるなら進む if(next_x>=0 && next_x < m && next_y>=0 && next_y < n && !visit[next] && G[next_y][next_x]=='.' ){ return ret + dfs_(G,n,m,visit, next, start, (toward+3)%4); }else{ //進めないならおしまい //次でstart地点に戻っていれば終了 if(next_x>=0 && next_x < m && next_y>=0 && next_y < n && next == start){ return ret; }else{ //そうでなければ不適切 return -1; } } } int main(){ int n,m; cin >> n >> m; vector<string> v(n); for(int i=0; i<n; i++){ cin >> v[i]; } vector<vector<int> > G(n*m); vector<int> s; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ if(v[i][j] == '.'){ s.push_back(i*m + j); for(int k=0; k<4; k++){ int xx = j + x[k]; int yy = i + y[k]; if(xx<0 || xx >= m || yy<0 || yy >= n) continue; if(v[yy][xx] == '.'){ G[m*i + j].push_back(yy*m + xx); } } } } } vector<bool> visit(n*m, false); bool valid = dfs(G, visit, s[0]) == s.size(); if(valid == false){ cout << "NO" << endl; return 0; } valid = false; for(int i=0; i<s.size() && valid == false; i++){ int start = s[i]; for(int j=0; j<4 && valid == false; j++){ fill(visit.begin(), visit.end(), false); int cnt = dfs_(v, n, m, visit, start, start, j); valid |= cnt == s.size(); } } cout << (valid?"YES":"NO") << endl; return 0; }