讨论/《高级算法》 - 螺旋矩阵/
《高级算法》 - 螺旋矩阵
共 1 个回复

外圈遍历 方法

//螺旋矩阵
		var spiralOrder = function(matrix) {
			let path = []; //结果记录
			let m = matrix.length; //行数
			let n = matrix[0].length; //列数
			let rowStart = 0;
			let rowEnd = m - 1;
			let colStart = 0;
			let colEnd = n - 1;
			// let count = 0;
			while (path.length < m * n) {
				//顶层从左到右
				for (let i = colStart; i <= colEnd; i++) {
					path.push(matrix[rowStart][i]);
					// count++;
				}

				//右侧从上到下
				if (rowStart + 1 <= rowEnd && path.length < m * n) {
					for (let i = rowStart + 1; i <= rowEnd; i++) {
						path.push(matrix[i][colEnd]);
						// count++;
					}
				}

				//底层从右到左
				if (colStart <= colEnd - 1 && path.length < m * n) {
					for (let i = colEnd - 1; i >= colStart; i--) {
						path.push(matrix[rowEnd][i]);
						// count++;
					}
				}

				//左侧从下到上
				if (rowStart + 1 <= rowEnd - 1 && path.length < m * n) {
					for (let i = rowEnd - 1; i >= rowStart + 1; i--) {
						path.push(matrix[i][colStart]);
						// count++;
					}
				}
				
				if(path.length < m * n){
					//一圈遍历完后
					rowStart++;
					rowEnd--;
					colStart++;
					colEnd--;
				}
				
			}
			return path;
		};