标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1167 Accepted Submission(s): 216
2
2 2
11
11
3 3
111
111
111
/** 题意:给一个n*m的01矩阵 然后要求从(0,0) 走到(n-1,m-1) 问走到的最小的串 做法:bfs + 贪心先找离(n-1,m-1),最近的1的位置,就是找所有的 前缀0,然后从最近的1开始搜,只需要搜索当前位置的左和下 然后直至(n-1,m-1) **/ #include <iostream> #include <algorithm> #include <cmath> #include <stdio.h> #include <string.h> #include <queue> using namespace std; #define maxn 1100 int vis[maxn][maxn]; char ch[maxn][maxn]; int n, m; int dx[4][2] = {1, 0, 0, 1, -1, 0, 0, -1}; int sx, sy; struct Node { int x; int y; Node() {} }; int check(int x, int y) { if(x >= 0 && x < n && y >= 0 && y < m) { return 1; } return 0; } void bfs(int x, int y) { Node tmp, now, temp; queue<Node>que; vis[x][y] = 1; temp.x = x; temp.y = y; que.push(temp); while(!que.empty()) { now = que.front(); que.pop(); for(int i = 0; i < 4; i++) { tmp.x = now.x + dx[i][0]; tmp.y = now.y + dx[i][1]; if(check(tmp.x, tmp.y) && vis[tmp.x][tmp.y] == 0) { vis[tmp.x][tmp.y] = 1; if(ch[tmp.x][tmp.y] == ‘0‘) { que.push(tmp); } if(tmp.x + tmp.y > sx + sy) { sx = tmp.x; sy = tmp.y; } } } } } void bfs1() { printf("1"); bool isok = false; bool isok1 = false; for(int i = sx + sy; i < n + m - 2; i++) { isok = false; for(int j = 0; j <= i; j++) { int x = j; int y = i - j; if(check(x, y) == 0 || vis[x][y] == 0) { continue; } if(isok1 && ch[x][y] == ‘1‘) { continue; } for(int p = 0; p < 2; p++) { int tx = x + dx[p][0]; int ty = y + dx[p][1]; if(check(tx, ty) == 0) { continue; } vis[tx][ty] = 1; if(ch[tx][ty] == ‘0‘) { isok = true; } } } isok1 = isok; if(isok) { printf("0"); } else { printf("1"); } } printf("\n"); } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d %d", &n, &m); memset(vis, 0, sizeof(vis)); for(int i = 0; i < n; i++) { scanf("%s", ch[i]); } sx = sy = 0; vis[0][0] = 1; if(ch[0][0] == ‘0‘) { bfs(0, 0); } //cout << sx << " " << sy << endl; if(ch[sx][sy] == ‘0‘) { printf("0\n"); } else { bfs1(); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/chenyang920/p/4691336.html