알고리즘 문제/BOJ
16973번 직사각형 탈출
parkit
2019. 4. 22. 10:32
728x90
반응형
https://www.acmicpc.net/problem/16973
범위 체크를 해주었지만, 방문 체크를 안 해주는 바람에
계속 메모리 초과가 떴다.
이런 실수는 하지 않아야 하는데, 주의할 필요가 있다.
왜 이런 실수를 했는지 모르겠다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 | #include <iostream> #include <queue> #include <stack> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> #include <map> #include <set> #include <sstream> #include <tuple> #pragma warning(disable:4996) #pragma comment(linker, "/STACK:336777216") using namespace std; // Map[행][열] = Map[y][x] // 행 : y, 열 : x int N = 0, M = 0; int sy = 0, sx = 0, rh = 0, rw = 0, ey = 0, ex = 0; int dy[4] = { 0, 1, 0, -1 }; int dx[4] = { 1, 0 ,-1, 0 }; int Map[1001][1001] = { 0, }, sum[1001][1001] = { 0, }; bool visit[1001][1001] = { false, }; queue<pair<int, int> > q; // area(다음 y 좌표, 다음 x 좌표, 직사각형 행의 크기, 직사각형 열의 크기) int area(int y, int x, int h, int w) { return sum[y + h - 1][x + w - 1] - sum[y - 1][x + w - 1] - sum[y + h - 1][x - 1] + sum[y - 1][x - 1]; } int BFS() { // 시작 visit[sy][sx] = true; // 시작 q.push({ sy, sx }); // 반환 값 int ret = 0; while (!q.empty()) { int qSize = q.size(); while (qSize--) { int r = q.front().first; int c = q.front().second; // pop q.pop(); // 도착했다면 return if (r == ey && c == ex) return ret; for (int i = 0; i < 4; i++) { int y = r + dy[i]; int x = c + dx[i]; // 범위 체크 및 방문 체크 if (y < 1 || y + rh - 1 > N || x < 1 || x + rw - 1> M || visit[y][x]) continue; // 사각형의 넓이 무조건 0이어야 한다. if (area(y, x, rh, rw) == 0) { q.push({ y , x }); visit[y][x] = true; } } } ++ret; } return -1; } int main(void) { scanf("%d %d", &N, &M); for (int i = 1; i <= N; i++) for (int j = 1; j <= M; j++) scanf("%d", &Map[i][j]); // 넓이 for (int i = 1; i <= N; i++) for (int j = 1; j <= M; j++) sum[i][j] = sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1] + Map[i][j]; // rh, rw = 직사각형의 크기, sy, sx = 시작 좌표, ey, ex = 도착 좌표 scanf("%d %d %d %d %d %d", &rh, &rw, &sy, &sx, &ey, &ex); printf("%d\n", BFS()); return 0; } | cs |
728x90
반응형